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/lz4cli/lz4.1
. .TH "LZ4" "1" "September 2018" "lz4 1.8.3" "User Commands" . .SH "NAME" \fBlz4\fR \- lz4, unlz4, lz4cat \- Compress or decompress \.lz4 files . .SH "SYNOPSIS" \fBlz4\fR [\fIOPTIONS\fR] [\-|INPUT\-FILE] \fIOUTPUT\-FILE\fR . .P \fBunlz4\fR is equivalent to \fBlz4 \-d\fR . .P \fBlz4cat\fR is equivalent to \fBlz4 \-dcfm\fR . .P When writing scripts that need to decompress files, it is recommended to always use the name \fBlz4\fR with appropriate arguments (\fBlz4 \-d\fR or \fBlz4 \-dc\fR) instead of the names \fBunlz4\fR and \fBlz4cat\fR\. . .SH "DESCRIPTION" \fBlz4\fR is an extremely fast lossless compression algorithm, based on \fBbyte\-aligned LZ77\fR family of compression scheme\. \fBlz4\fR offers compression speeds of 400 MB/s per core, linearly scalable with multi\-core CPUs\. It features an extremely fast decoder, with speed in multiple GB/s per core, typically reaching RAM speed limit on multi\-core systems\. The native file format is the \fB\.lz4\fR format\. . .SS "Difference between lz4 and gzip" \fBlz4\fR supports a command line syntax similar \fIbut not identical\fR to \fBgzip(1)\fR\. Differences are : . .IP "\(bu" 4 \fBlz4\fR preserves original files . .IP "\(bu" 4 \fBlz4\fR compresses a single file by default (see \fB\-m\fR for multiple files) . .IP "\(bu" 4 \fBlz4 file1 file2\fR means : compress file1 \fIinto\fR file2 . .IP "\(bu" 4 \fBlz4 file\.lz4\fR will default to decompression (use \fB\-z\fR to force compression) . .IP "\(bu" 4 \fBlz4\fR shows real\-time notification statistics during compression or decompression of a single file (use \fB\-q\fR to silence them) . .IP "\(bu" 4 If no destination name is provided, result is sent to \fBstdout\fR \fIexcept if stdout is the console\fR\. . .IP "\(bu" 4 If no destination name is provided, \fBand\fR if \fBstdout\fR is the console, \fBfile\fR is compressed into \fBfile\.lz4\fR\. . .IP "\(bu" 4 As a consequence of previous rules, note the following example : \fBlz4 file | consumer\fR sends compressed data to \fBconsumer\fR through \fBstdout\fR, hence it does \fInot\fR create \fBfile\.lz4\fR\. . .IP "\(bu" 4 Another consequence of those rules is that to run \fBlz4\fR under \fBnohup\fR, you should provide a destination file: \fBnohup lz4 file file\.lz4\fR, because \fBnohup\fR writes the specified command\'s output to a file\. . .IP "" 0 . .P Default behaviors can be modified by opt\-in commands, detailed below\. . .IP "\(bu" 4 \fBlz4 \-m\fR makes it possible to provide multiple input filenames, which will be compressed into files using suffix \fB\.lz4\fR\. Progress notifications are also disabled by default (use \fB\-v\fR to enable them)\. This mode has a behavior which more closely mimics \fBgzip\fR command line, with the main remaining difference being that source files are preserved by default\. . .IP "\(bu" 4 Similarly, \fBlz4 \-m \-d\fR can decompress multiple \fB*\.lz4\fR files\. . .IP "\(bu" 4 It\'s possible to opt\-in to erase source files on successful compression or decompression, using \fB\-\-rm\fR command\. . .IP "\(bu" 4 Consequently, \fBlz4 \-m \-\-rm\fR behaves the same as \fBgzip\fR\. . .IP "" 0 . .SS "Concatenation of \.lz4 files" It is possible to concatenate \fB\.lz4\fR files as is\. \fBlz4\fR will decompress such files as if they were a single \fB\.lz4\fR file\. For example: . .IP "" 4 . .nf lz4 file1 > foo\.lz4 lz4 file2 >> foo\.lz4 . .fi . .IP "" 0 . .P Then \fBlz4cat foo\.lz4\fR is equivalent to \fBcat file1 file2\fR\. . .SH "OPTIONS" . .SS "Short commands concatenation" In some cases, some options can be expressed using short command \fB\-x\fR or long command \fB\-\-long\-word\fR\. Short commands can be concatenated together\. For example, \fB\-d \-c\fR is equivalent to \fB\-dc\fR\. Long commands cannot be concatenated\. They must be clearly separated by a space\. . .SS "Multiple commands" When multiple contradictory commands are issued on a same command line, only the latest one will be applied\. . .SS "Operation mode" . .TP \fB\-z\fR \fB\-\-compress\fR Compress\. This is the default operation mode when no operation mode option is specified, no other operation mode is implied from the command name (for example, \fBunlz4\fR implies \fB\-\-decompress\fR), nor from the input file name (for example, a file extension \fB\.lz4\fR implies \fB\-\-decompress\fR by default)\. \fB\-z\fR can also be used to force compression of an already compressed \fB\.lz4\fR file\. . .TP \fB\-d\fR \fB\-\-decompress\fR \fB\-\-uncompress\fR Decompress\. \fB\-\-decompress\fR is also the default operation when the input filename has an \fB\.lz4\fR extension\. . .TP \fB\-t\fR \fB\-\-test\fR Test the integrity of compressed \fB\.lz4\fR files\. The decompressed data is discarded\. No files are created nor removed\. . .TP \fB\-b#\fR Benchmark mode, using \fB#\fR compression level\. . .SS "Operation modifiers" . .TP \fB\-#\fR Compression level, with # being any value from 1 to 12\. Higher values trade compression speed for compression ratio\. Values above 12 are considered the same as 12\. Recommended values are 1 for fast compression (default), and 9 for high compression\. Speed/compression trade\-off will vary depending on data to compress\. Decompression speed remains fast at all settings\. . .TP \fB\-D dictionaryName\fR Compress, decompress or benchmark using dictionary \fIdictionaryName\fR\. Compression and decompression must use the same dictionary to be compatible\. Using a different dictionary during decompression will either abort due to decompression error, or generate a checksum error\. . .TP \fB\-f\fR \fB\-\-[no\-]force\fR This option has several effects: . .IP If the target file already exists, overwrite it without prompting\. . .IP When used with \fB\-\-decompress\fR and \fBlz4\fR cannot recognize the type of the source file, copy the source file as is to standard output\. This allows \fBlz4cat \-\-force\fR to be used like \fBcat (1)\fR for files that have not been compressed with \fBlz4\fR\. . .TP \fB\-c\fR \fB\-\-stdout\fR \fB\-\-to\-stdout\fR Force write to standard output, even if it is the console\. . .TP \fB\-m\fR \fB\-\-multiple\fR Multiple input files\. Compressed file names will be appended a \fB\.lz4\fR suffix\. This mode also reduces notification level\. \fBlz4 \-m\fR has a behavior equivalent to \fBgzip \-k\fR (it preserves source files by default)\. . .TP \fB\-r\fR operate recursively on directories\. This mode also sets \fB\-m\fR (multiple input files)\. . .TP \fB\-B#\fR Block size [4\-7](default : 7) . .br \fB\-B4\fR= 64KB ; \fB\-B5\fR= 256KB ; \fB\-B6\fR= 1MB ; \fB\-B7\fR= 4MB . .TP \fB\-BD\fR Block Dependency (improves compression ratio on small blocks) . .TP \fB\-\-fast[=#]\fR switch to ultra\-fast compression levels\. If \fB=#\fR is not present, it defaults to \fB1\fR\. The higher the value, the faster the compression speed, at the cost of some compression ratio\. This setting overwrites compression level if one was set previously\. Similarly, if a compression level is set after \fB\-\-fast\fR, it overrides it\. . .TP \fB\-\-[no\-]frame\-crc\fR Select frame checksum (default:enabled) . .TP \fB\-\-[no\-]content\-size\fR Header includes original size (default:not present) . .br Note : this option can only be activated when the original size can be determined, hence for a file\. It won\'t work with unknown source size, such as stdin or pipe\. . .TP \fB\-\-[no\-]sparse\fR Sparse mode support (default:enabled on file, disabled on stdout) . .TP \fB\-l\fR Use Legacy format (typically for Linux Kernel compression) . .br Note : \fB\-l\fR is not compatible with \fB\-m\fR (\fB\-\-multiple\fR) nor \fB\-r\fR . .SS "Other options" . .TP \fB\-v\fR \fB\-\-verbose\fR Verbose mode . .TP \fB\-q\fR \fB\-\-quiet\fR Suppress warnings and real\-time statistics; specify twice to suppress errors too . .TP \fB\-h\fR \fB\-H\fR \fB\-\-help\fR Display help/long help and exit . .TP \fB\-V\fR \fB\-\-version\fR Display Version number and exit . .TP \fB\-k\fR \fB\-\-keep\fR Preserve source files (default behavior) . .TP \fB\-\-rm\fR Delete source files on successful compression or decompression . .TP \fB\-\-\fR Treat all subsequent arguments as files . .SS "Benchmark mode" . .TP \fB\-b#\fR Benchmark file(s), using # compression level . .TP \fB\-e#\fR Benchmark multiple compression levels, from b# to e# (included) . .TP \fB\-i#\fR Minimum evaluation time in seconds [1\-9] (default : 3) . .SH "BUGS" Report bugs at: https://github\.com/lz4/lz4/issues . .SH "AUTHOR" Yann Collet
8,483
232
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/lz4frame.h
/* clang-format off */ /* LZ4 auto-framing library Header File Copyright (C) 2011-2017, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) 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. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. You can contact the author at : - LZ4 source repository : https://github.com/lz4/lz4 - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c */ /* LZ4F is a stand-alone API to create LZ4-compressed frames * conformant with specification v1.6.1. * It also offers streaming capabilities. * lz4.h is not required when using lz4frame.h, * except to get constant such as LZ4_VERSION_NUMBER. * */ #ifndef LZ4F_H_09782039843 #define LZ4F_H_09782039843 #if defined (__cplusplus) extern "C" { #endif /* --- Dependency --- */ /** Introduction lz4frame.h implements LZ4 frame specification (doc/lz4_Frame_format.md). lz4frame.h provides frame compression functions that take care of encoding standard metadata alongside LZ4-compressed blocks. */ /*-*************************************************************** * Compiler specifics *****************************************************************/ /* LZ4_DLL_EXPORT : * Enable exporting of functions when building a Windows DLL * LZ4FLIB_API : * Control library symbols visibility. */ #if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1) # define LZ4FLIB_API __declspec(dllexport) #elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1) # define LZ4FLIB_API __declspec(dllimport) #elif defined(__GNUC__) && (__GNUC__ >= 4) # define LZ4FLIB_API __attribute__ ((__visibility__ ("default"))) #else # define LZ4FLIB_API #endif #ifdef LZ4F_DISABLE_DEPRECATE_WARNINGS # define LZ4F_DEPRECATE(x) x #else # if defined(_MSC_VER) # define LZ4F_DEPRECATE(x) x /* __declspec(deprecated) x - only works with C++ */ # elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 6)) # define LZ4F_DEPRECATE(x) x __attribute__((deprecated)) # else # define LZ4F_DEPRECATE(x) x /* no deprecation warning for this compiler */ # endif #endif /*-************************************ * Error management **************************************/ typedef size_t LZ4F_errorCode_t; LZ4FLIB_API unsigned LZ4F_isError(LZ4F_errorCode_t code); /**< tells when a function result is an error code */ LZ4FLIB_API const char* LZ4F_getErrorName(LZ4F_errorCode_t code); /**< return error code string; for debugging */ /*-************************************ * Frame compression types **************************************/ /* #define LZ4F_ENABLE_OBSOLETE_ENUMS // uncomment to enable obsolete enums */ #ifdef LZ4F_ENABLE_OBSOLETE_ENUMS # define LZ4F_OBSOLETE_ENUM(x) , LZ4F_DEPRECATE(x) = LZ4F_##x #else # define LZ4F_OBSOLETE_ENUM(x) #endif /* The larger the block size, the (slightly) better the compression ratio, * though there are diminishing returns. * Larger blocks also increase memory usage on both compression and decompression sides. */ typedef enum { LZ4F_default=0, LZ4F_max64KB=4, LZ4F_max256KB=5, LZ4F_max1MB=6, LZ4F_max4MB=7 LZ4F_OBSOLETE_ENUM(max64KB) LZ4F_OBSOLETE_ENUM(max256KB) LZ4F_OBSOLETE_ENUM(max1MB) LZ4F_OBSOLETE_ENUM(max4MB) } LZ4F_blockSizeID_t; /* Linked blocks sharply reduce inefficiencies when using small blocks, * they compress better. * However, some LZ4 decoders are only compatible with independent blocks */ typedef enum { LZ4F_blockLinked=0, LZ4F_blockIndependent LZ4F_OBSOLETE_ENUM(blockLinked) LZ4F_OBSOLETE_ENUM(blockIndependent) } LZ4F_blockMode_t; typedef enum { LZ4F_noContentChecksum=0, LZ4F_contentChecksumEnabled LZ4F_OBSOLETE_ENUM(noContentChecksum) LZ4F_OBSOLETE_ENUM(contentChecksumEnabled) } LZ4F_contentChecksum_t; typedef enum { LZ4F_noBlockChecksum=0, LZ4F_blockChecksumEnabled } LZ4F_blockChecksum_t; typedef enum { LZ4F_frame=0, LZ4F_skippableFrame LZ4F_OBSOLETE_ENUM(skippableFrame) } LZ4F_frameType_t; #ifdef LZ4F_ENABLE_OBSOLETE_ENUMS typedef LZ4F_blockSizeID_t blockSizeID_t; typedef LZ4F_blockMode_t blockMode_t; typedef LZ4F_frameType_t frameType_t; typedef LZ4F_contentChecksum_t contentChecksum_t; #endif /*! LZ4F_frameInfo_t : * makes it possible to set or read frame parameters. * Structure must be first init to 0, using memset() or LZ4F_INIT_FRAMEINFO, * setting all parameters to default. * It's then possible to update selectively some parameters */ typedef struct { LZ4F_blockSizeID_t blockSizeID; /* max64KB, max256KB, max1MB, max4MB; 0 == default */ LZ4F_blockMode_t blockMode; /* LZ4F_blockLinked, LZ4F_blockIndependent; 0 == default */ LZ4F_contentChecksum_t contentChecksumFlag; /* 1: frame terminated with 32-bit checksum of decompressed data; 0: disabled (default) */ LZ4F_frameType_t frameType; /* read-only field : LZ4F_frame or LZ4F_skippableFrame */ unsigned long long contentSize; /* Size of uncompressed content ; 0 == unknown */ unsigned dictID; /* Dictionary ID, sent by compressor to help decoder select correct dictionary; 0 == no dictID provided */ LZ4F_blockChecksum_t blockChecksumFlag; /* 1: each block followed by a checksum of block's compressed data; 0: disabled (default) */ } LZ4F_frameInfo_t; #define LZ4F_INIT_FRAMEINFO { 0, 0, 0, 0, 0, 0, 0 } /* v1.8.3+ */ /*! LZ4F_preferences_t : * makes it possible to supply advanced compression instructions to streaming interface. * Structure must be first init to 0, using memset() or LZ4F_INIT_PREFERENCES, * setting all parameters to default. * All reserved fields must be set to zero. */ typedef struct { LZ4F_frameInfo_t frameInfo; int compressionLevel; /* 0: default (fast mode); values > LZ4HC_CLEVEL_MAX count as LZ4HC_CLEVEL_MAX; values < 0 trigger "fast acceleration" */ unsigned autoFlush; /* 1: always flush; reduces usage of internal buffers */ unsigned favorDecSpeed; /* 1: parser favors decompression speed vs compression ratio. Only works for high compression modes (>= LZ4HC_CLEVEL_OPT_MIN) */ /* v1.8.2+ */ unsigned reserved[3]; /* must be zero for forward compatibility */ } LZ4F_preferences_t; #define LZ4F_INIT_PREFERENCES { LZ4F_INIT_FRAMEINFO, 0, 0, 0, { 0, 0, 0 } } /* v1.8.3+ */ /*-********************************* * Simple compression function ***********************************/ LZ4FLIB_API int LZ4F_compressionLevel_max(void); /*! LZ4F_compressFrameBound() : * Returns the maximum possible compressed size with LZ4F_compressFrame() given srcSize and preferences. * `preferencesPtr` is optional. It can be replaced by NULL, in which case, the function will assume default preferences. * Note : this result is only usable with LZ4F_compressFrame(). * It may also be used with LZ4F_compressUpdate() _if no flush() operation_ is performed. */ LZ4FLIB_API size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr); /*! LZ4F_compressFrame() : * Compress an entire srcBuffer into a valid LZ4 frame. * dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). * The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default. * @return : number of bytes written into dstBuffer. * or an error code if it fails (can be tested using LZ4F_isError()) */ LZ4FLIB_API size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity, const void* srcBuffer, size_t srcSize, const LZ4F_preferences_t* preferencesPtr); /*-*********************************** * Advanced compression functions *************************************/ typedef struct LZ4F_cctx_s LZ4F_cctx; /* incomplete type */ typedef LZ4F_cctx* LZ4F_compressionContext_t; /* for compatibility with previous API version */ typedef struct { unsigned stableSrc; /* 1 == src content will remain present on future calls to LZ4F_compress(); skip copying src content within tmp buffer */ unsigned reserved[3]; } LZ4F_compressOptions_t; /*--- Resource Management ---*/ #define LZ4F_VERSION 100 /* This number can be used to check for an incompatible API breaking change */ LZ4FLIB_API unsigned LZ4F_getVersion(void); /*! LZ4F_createCompressionContext() : * The first thing to do is to create a compressionContext object, which will be used in all compression operations. * This is achieved using LZ4F_createCompressionContext(), which takes as argument a version. * The version provided MUST be LZ4F_VERSION. It is intended to track potential version mismatch, notably when using DLL. * The function will provide a pointer to a fully allocated LZ4F_cctx object. * If @return != zero, there was an error during context creation. * Object can release its memory using LZ4F_freeCompressionContext(); */ LZ4FLIB_API LZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_cctx** cctxPtr, unsigned version); LZ4FLIB_API LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctx); /*---- Compression ----*/ #define LZ4F_HEADER_SIZE_MAX 19 /* LZ4 Frame header size can vary from 7 to 19 bytes */ /*! LZ4F_compressBegin() : * will write the frame header into dstBuffer. * dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes. * `prefsPtr` is optional : you can provide NULL as argument, all preferences will then be set to default. * @return : number of bytes written into dstBuffer for the header * or an error code (which can be tested using LZ4F_isError()) */ LZ4FLIB_API size_t LZ4F_compressBegin(LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const LZ4F_preferences_t* prefsPtr); /*! LZ4F_compressBound() : * Provides minimum dstCapacity required to guarantee compression success * given a srcSize and preferences, covering worst case scenario. * prefsPtr is optional : when NULL is provided, preferences will be set to cover worst case scenario. * Estimation is valid for either LZ4F_compressUpdate(), LZ4F_flush() or LZ4F_compressEnd(), * Estimation includes the possibility that internal buffer might already be filled by up to (blockSize-1) bytes. * It also includes frame footer (ending + checksum), which would have to be generated by LZ4F_compressEnd(). * Estimation doesn't include frame header, as it was already generated by LZ4F_compressBegin(). * Result is always the same for a srcSize and prefsPtr, so it can be trusted to size reusable buffers. * When srcSize==0, LZ4F_compressBound() provides an upper bound for LZ4F_flush() and LZ4F_compressEnd() operations. */ LZ4FLIB_API size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* prefsPtr); /*! LZ4F_compressUpdate() : * LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary. * Important rule: dstCapacity MUST be large enough to ensure operation success even in worst case situations. * This value is provided by LZ4F_compressBound(). * If this condition is not respected, LZ4F_compress() will fail (result is an errorCode). * LZ4F_compressUpdate() doesn't guarantee error recovery. * When an error occurs, compression context must be freed or resized. * `cOptPtr` is optional : NULL can be provided, in which case all options are set to default. * @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered). * or an error code if it fails (which can be tested using LZ4F_isError()) */ LZ4FLIB_API size_t LZ4F_compressUpdate(LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const void* srcBuffer, size_t srcSize, const LZ4F_compressOptions_t* cOptPtr); /*! LZ4F_flush() : * When data must be generated and sent immediately, without waiting for a block to be completely filled, * it's possible to call LZ4_flush(). It will immediately compress any data buffered within cctx. * `dstCapacity` must be large enough to ensure the operation will be successful. * `cOptPtr` is optional : it's possible to provide NULL, all options will be set to default. * @return : nb of bytes written into dstBuffer (can be zero, when there is no data stored within cctx) * or an error code if it fails (which can be tested using LZ4F_isError()) */ LZ4FLIB_API size_t LZ4F_flush(LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const LZ4F_compressOptions_t* cOptPtr); /*! LZ4F_compressEnd() : * To properly finish an LZ4 frame, invoke LZ4F_compressEnd(). * It will flush whatever data remained within `cctx` (like LZ4_flush()) * and properly finalize the frame, with an endMark and a checksum. * `cOptPtr` is optional : NULL can be provided, in which case all options will be set to default. * @return : nb of bytes written into dstBuffer, necessarily >= 4 (endMark), * or an error code if it fails (which can be tested using LZ4F_isError()) * A successful call to LZ4F_compressEnd() makes `cctx` available again for another compression task. */ LZ4FLIB_API size_t LZ4F_compressEnd(LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const LZ4F_compressOptions_t* cOptPtr); /*-********************************* * Decompression functions ***********************************/ typedef struct LZ4F_dctx_s LZ4F_dctx; /* incomplete type */ typedef LZ4F_dctx* LZ4F_decompressionContext_t; /* compatibility with previous API versions */ typedef struct { unsigned stableDst; /* pledges that last 64KB decompressed data will remain available unmodified. This optimization skips storage operations in tmp buffers. */ unsigned reserved[3]; /* must be set to zero for forward compatibility */ } LZ4F_decompressOptions_t; /* Resource management */ /*! LZ4F_createDecompressionContext() : * Create an LZ4F_dctx object, to track all decompression operations. * The version provided MUST be LZ4F_VERSION. * The function provides a pointer to an allocated and initialized LZ4F_dctx object. * The result is an errorCode, which can be tested using LZ4F_isError(). * dctx memory can be released using LZ4F_freeDecompressionContext(); * Result of LZ4F_freeDecompressionContext() indicates current state of decompressionContext when being released. * That is, it should be == 0 if decompression has been completed fully and correctly. */ LZ4FLIB_API LZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_dctx** dctxPtr, unsigned version); LZ4FLIB_API LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx); /*-*********************************** * Streaming decompression functions *************************************/ /*! LZ4F_getFrameInfo() : * This function extracts frame parameters (max blockSize, dictID, etc.). * Its usage is optional. * Extracted information is typically useful for allocation and dictionary. * This function works in 2 situations : * - At the beginning of a new frame, in which case * it will decode information from `srcBuffer`, starting the decoding process. * Input size must be large enough to successfully decode the entire frame header. * Frame header size is variable, but is guaranteed to be <= LZ4F_HEADER_SIZE_MAX bytes. * It's allowed to provide more input data than this minimum. * - After decoding has been started. * In which case, no input is read, frame parameters are extracted from dctx. * - If decoding has barely started, but not yet extracted information from header, * LZ4F_getFrameInfo() will fail. * The number of bytes consumed from srcBuffer will be updated within *srcSizePtr (necessarily <= original value). * Decompression must resume from (srcBuffer + *srcSizePtr). * @return : an hint about how many srcSize bytes LZ4F_decompress() expects for next call, * or an error code which can be tested using LZ4F_isError(). * note 1 : in case of error, dctx is not modified. Decoding operation can resume from beginning safely. * note 2 : frame parameters are *copied into* an already allocated LZ4F_frameInfo_t structure. */ LZ4FLIB_API size_t LZ4F_getFrameInfo(LZ4F_dctx* dctx, LZ4F_frameInfo_t* frameInfoPtr, const void* srcBuffer, size_t* srcSizePtr); /*! LZ4F_decompress() : * Call this function repetitively to regenerate compressed data from `srcBuffer`. * The function will read up to *srcSizePtr bytes from srcBuffer, * and decompress data into dstBuffer, of capacity *dstSizePtr. * * The nb of bytes consumed from srcBuffer will be written into *srcSizePtr (necessarily <= original value). * The nb of bytes decompressed into dstBuffer will be written into *dstSizePtr (necessarily <= original value). * * The function does not necessarily read all input bytes, so always check value in *srcSizePtr. * Unconsumed source data must be presented again in subsequent invocations. * * `dstBuffer` can freely change between each consecutive function invocation. * `dstBuffer` content will be overwritten. * * @return : an hint of how many `srcSize` bytes LZ4F_decompress() expects for next call. * Schematically, it's the size of the current (or remaining) compressed block + header of next block. * Respecting the hint provides some small speed benefit, because it skips intermediate buffers. * This is just a hint though, it's always possible to provide any srcSize. * * When a frame is fully decoded, @return will be 0 (no more data expected). * When provided with more bytes than necessary to decode a frame, * LZ4F_decompress() will stop reading exactly at end of current frame, and @return 0. * * If decompression failed, @return is an error code, which can be tested using LZ4F_isError(). * After a decompression error, the `dctx` context is not resumable. * Use LZ4F_resetDecompressionContext() to return to clean state. * * After a frame is fully decoded, dctx can be used again to decompress another frame. */ LZ4FLIB_API size_t LZ4F_decompress(LZ4F_dctx* dctx, void* dstBuffer, size_t* dstSizePtr, const void* srcBuffer, size_t* srcSizePtr, const LZ4F_decompressOptions_t* dOptPtr); /*! LZ4F_resetDecompressionContext() : added in v1.8.0 * In case of an error, the context is left in "undefined" state. * In which case, it's necessary to reset it, before re-using it. * This method can also be used to abruptly stop any unfinished decompression, * and start a new one using same context resources. */ LZ4FLIB_API void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx); /* always successful */ #if defined (__cplusplus) } #endif #endif /* LZ4F_H_09782039843 */ #if defined(LZ4F_STATIC_LINKING_ONLY) && !defined(LZ4F_H_STATIC_09782039843) #define LZ4F_H_STATIC_09782039843 #if defined (__cplusplus) extern "C" { #endif /* These declarations are not stable and may change in the future. They are * therefore only safe to depend on when the caller is statically linked * against the library. To access their declarations, define * LZ4F_STATIC_LINKING_ONLY. * * There is a further protection mechanism where these symbols aren't published * into shared/dynamic libraries. You can override this behavior and force * them to be published by defining LZ4F_PUBLISH_STATIC_FUNCTIONS. Use at * your own risk. */ #ifdef LZ4F_PUBLISH_STATIC_FUNCTIONS #define LZ4FLIB_STATIC_API LZ4FLIB_API #else #define LZ4FLIB_STATIC_API #endif /* --- Error List --- */ #define LZ4F_LIST_ERRORS(ITEM) \ ITEM(OK_NoError) \ ITEM(ERROR_GENERIC) \ ITEM(ERROR_maxBlockSize_invalid) \ ITEM(ERROR_blockMode_invalid) \ ITEM(ERROR_contentChecksumFlag_invalid) \ ITEM(ERROR_compressionLevel_invalid) \ ITEM(ERROR_headerVersion_wrong) \ ITEM(ERROR_blockChecksum_invalid) \ ITEM(ERROR_reservedFlag_set) \ ITEM(ERROR_allocation_failed) \ ITEM(ERROR_srcSize_tooLarge) \ ITEM(ERROR_dstMaxSize_tooSmall) \ ITEM(ERROR_frameHeader_incomplete) \ ITEM(ERROR_frameType_unknown) \ ITEM(ERROR_frameSize_wrong) \ ITEM(ERROR_srcPtr_wrong) \ ITEM(ERROR_decompressionFailed) \ ITEM(ERROR_headerChecksum_invalid) \ ITEM(ERROR_contentChecksum_invalid) \ ITEM(ERROR_frameDecoding_alreadyStarted) \ ITEM(ERROR_maxCode) #define LZ4F_GENERATE_ENUM(ENUM) LZ4F_##ENUM, /* enum list is exposed, to handle specific errors */ typedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM) } LZ4F_errorCodes; LZ4FLIB_STATIC_API LZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult); /********************************** * Bulk processing dictionary API *********************************/ typedef struct LZ4F_CDict_s LZ4F_CDict; /*! LZ4_createCDict() : * When compressing multiple messages / blocks with the same dictionary, it's recommended to load it just once. * LZ4_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay. * LZ4_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. * `dictBuffer` can be released after LZ4_CDict creation, since its content is copied within CDict */ LZ4FLIB_STATIC_API LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize); LZ4FLIB_STATIC_API void LZ4F_freeCDict(LZ4F_CDict* CDict); /*! LZ4_compressFrame_usingCDict() : * Compress an entire srcBuffer into a valid LZ4 frame using a digested Dictionary. * cctx must point to a context created by LZ4F_createCompressionContext(). * If cdict==NULL, compress without a dictionary. * dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). * If this condition is not respected, function will fail (@return an errorCode). * The LZ4F_preferences_t structure is optional : you may provide NULL as argument, * but it's not recommended, as it's the only way to provide dictID in the frame header. * @return : number of bytes written into dstBuffer. * or an error code if it fails (can be tested using LZ4F_isError()) */ LZ4FLIB_STATIC_API size_t LZ4F_compressFrame_usingCDict( LZ4F_cctx* cctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize, const LZ4F_CDict* cdict, const LZ4F_preferences_t* preferencesPtr); /*! LZ4F_compressBegin_usingCDict() : * Inits streaming dictionary compression, and writes the frame header into dstBuffer. * dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes. * `prefsPtr` is optional : you may provide NULL as argument, * however, it's the only way to provide dictID in the frame header. * @return : number of bytes written into dstBuffer for the header, * or an error code (which can be tested using LZ4F_isError()) */ LZ4FLIB_STATIC_API size_t LZ4F_compressBegin_usingCDict( LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const LZ4F_CDict* cdict, const LZ4F_preferences_t* prefsPtr); /*! LZ4F_decompress_usingDict() : * Same as LZ4F_decompress(), using a predefined dictionary. * Dictionary is used "in place", without any preprocessing. * It must remain accessible throughout the entire frame decoding. */ LZ4FLIB_STATIC_API size_t LZ4F_decompress_usingDict( LZ4F_dctx* dctxPtr, void* dstBuffer, size_t* dstSizePtr, const void* srcBuffer, size_t* srcSizePtr, const void* dict, size_t dictSize, const LZ4F_decompressOptions_t* decompressOptionsPtr); #if defined (__cplusplus) } #endif #endif /* defined(LZ4F_STATIC_LINKING_ONLY) && !defined(LZ4F_H_STATIC_09782039843) */
25,266
542
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/lz4hc.h
/* clang-format off */ /* LZ4 HC - High Compression Mode of LZ4 Header File Copyright (C) 2011-2017, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) 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. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. You can contact the author at : - LZ4 source repository : https://github.com/lz4/lz4 - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c */ #ifndef LZ4_HC_H_19834876238432 #define LZ4_HC_H_19834876238432 #if defined (__cplusplus) extern "C" { #endif /* --- Dependency --- */ /* note : lz4hc requires lz4.h/lz4.c for compilation */ #include "third_party/lz4cli/lz4.h" /* stddef, LZ4LIB_API, LZ4_DEPRECATED */ /* --- Useful constants --- */ #define LZ4HC_CLEVEL_MIN 3 #define LZ4HC_CLEVEL_DEFAULT 9 #define LZ4HC_CLEVEL_OPT_MIN 10 #define LZ4HC_CLEVEL_MAX 12 /*-************************************ * Block Compression **************************************/ /*! LZ4_compress_HC() : * Compress data from `src` into `dst`, using the more powerful but slower "HC" algorithm. * `dst` must be already allocated. * Compression is guaranteed to succeed if `dstCapacity >= LZ4_compressBound(srcSize)` (see "lz4.h") * Max supported `srcSize` value is LZ4_MAX_INPUT_SIZE (see "lz4.h") * `compressionLevel` : any value between 1 and LZ4HC_CLEVEL_MAX will work. * Values > LZ4HC_CLEVEL_MAX behave the same as LZ4HC_CLEVEL_MAX. * @return : the number of bytes written into 'dst' * or 0 if compression fails. */ LZ4LIB_API int LZ4_compress_HC (const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel); /* Note : * Decompression functions are provided within "lz4.h" (BSD license) */ /*! LZ4_compress_HC_extStateHC() : * Same as LZ4_compress_HC(), but using an externally allocated memory segment for `state`. * `state` size is provided by LZ4_sizeofStateHC(). * Memory segment must be aligned on 8-bytes boundaries (which a normal malloc() should do properly). */ LZ4LIB_API int LZ4_sizeofStateHC(void); LZ4LIB_API int LZ4_compress_HC_extStateHC(void* state, const char* src, char* dst, int srcSize, int maxDstSize, int compressionLevel); /*-************************************ * Streaming Compression * Bufferless synchronous API **************************************/ typedef union LZ4_streamHC_u LZ4_streamHC_t; /* incomplete type (defined later) */ /*! LZ4_createStreamHC() and LZ4_freeStreamHC() : * These functions create and release memory for LZ4 HC streaming state. * Newly created states are automatically initialized. * Existing states can be re-used several times, using LZ4_resetStreamHC(). * These methods are API and ABI stable, they can be used in combination with a DLL. */ LZ4LIB_API LZ4_streamHC_t* LZ4_createStreamHC(void); LZ4LIB_API int LZ4_freeStreamHC (LZ4_streamHC_t* streamHCPtr); LZ4LIB_API void LZ4_resetStreamHC (LZ4_streamHC_t* streamHCPtr, int compressionLevel); LZ4LIB_API int LZ4_loadDictHC (LZ4_streamHC_t* streamHCPtr, const char* dictionary, int dictSize); LZ4LIB_API int LZ4_compress_HC_continue (LZ4_streamHC_t* streamHCPtr, const char* src, char* dst, int srcSize, int maxDstSize); LZ4LIB_API int LZ4_saveDictHC (LZ4_streamHC_t* streamHCPtr, char* safeBuffer, int maxDictSize); /* These functions compress data in successive blocks of any size, using previous blocks as dictionary. One key assumption is that previous blocks (up to 64 KB) remain read-accessible while compressing next blocks. There is an exception for ring buffers, which can be smaller than 64 KB. Ring buffers scenario is automatically detected and handled by LZ4_compress_HC_continue(). Before starting compression, state must be properly initialized, using LZ4_resetStreamHC(). A first "fictional block" can then be designated as initial dictionary, using LZ4_loadDictHC() (Optional). Then, use LZ4_compress_HC_continue() to compress each successive block. Previous memory blocks (including initial dictionary when present) must remain accessible and unmodified during compression. 'dst' buffer should be sized to handle worst case scenarios (see LZ4_compressBound()), to ensure operation success. Because in case of failure, the API does not guarantee context recovery, and context will have to be reset. If `dst` buffer budget cannot be >= LZ4_compressBound(), consider using LZ4_compress_HC_continue_destSize() instead. If, for any reason, previous data block can't be preserved unmodified in memory for next compression block, you can save it to a more stable memory space, using LZ4_saveDictHC(). Return value of LZ4_saveDictHC() is the size of dictionary effectively saved into 'safeBuffer'. */ /*-************************************************************** * PRIVATE DEFINITIONS : * Do not use these definitions. * They are exposed to allow static allocation of `LZ4_streamHC_t`. * Using these definitions makes the code vulnerable to potential API break when upgrading LZ4 ****************************************************************/ #define LZ4HC_DICTIONARY_LOGSIZE 16 #define LZ4HC_MAXD (1<<LZ4HC_DICTIONARY_LOGSIZE) #define LZ4HC_MAXD_MASK (LZ4HC_MAXD - 1) #define LZ4HC_HASH_LOG 15 #define LZ4HC_HASHTABLESIZE (1 << LZ4HC_HASH_LOG) #define LZ4HC_HASH_MASK (LZ4HC_HASHTABLESIZE - 1) #if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) typedef struct LZ4HC_CCtx_internal LZ4HC_CCtx_internal; struct LZ4HC_CCtx_internal { uint32_t hashTable[LZ4HC_HASHTABLESIZE]; uint16_t chainTable[LZ4HC_MAXD]; const uint8_t* end; /* next block here to continue on current prefix */ const uint8_t* base; /* All index relative to this position */ const uint8_t* dictBase; /* alternate base for extDict */ uint32_t dictLimit; /* below that point, need extDict */ uint32_t lowLimit; /* below that point, no more dict */ uint32_t nextToUpdate; /* index from which to continue dictionary update */ short compressionLevel; short favorDecSpeed; const LZ4HC_CCtx_internal* dictCtx; }; #else typedef struct LZ4HC_CCtx_internal LZ4HC_CCtx_internal; struct LZ4HC_CCtx_internal { unsigned int hashTable[LZ4HC_HASHTABLESIZE]; unsigned short chainTable[LZ4HC_MAXD]; const unsigned char* end; /* next block here to continue on current prefix */ const unsigned char* base; /* All index relative to this position */ const unsigned char* dictBase; /* alternate base for extDict */ unsigned int dictLimit; /* below that point, need extDict */ unsigned int lowLimit; /* below that point, no more dict */ unsigned int nextToUpdate; /* index from which to continue dictionary update */ short compressionLevel; short favorDecSpeed; const LZ4HC_CCtx_internal* dictCtx; }; #endif #define LZ4_STREAMHCSIZE (4*LZ4HC_HASHTABLESIZE + 2*LZ4HC_MAXD + 56) /* 262200 */ #define LZ4_STREAMHCSIZE_SIZET (LZ4_STREAMHCSIZE / sizeof(size_t)) union LZ4_streamHC_u { size_t table[LZ4_STREAMHCSIZE_SIZET]; LZ4HC_CCtx_internal internal_donotuse; }; /* previously typedef'd to LZ4_streamHC_t */ /* LZ4_streamHC_t : This structure allows static allocation of LZ4 HC streaming state. State must be initialized using LZ4_resetStreamHC() before first use. Static allocation shall only be used in combination with static linking. When invoking LZ4 from a DLL, use create/free functions instead, which are API and ABI stable. */ /*-************************************ * Deprecated Functions **************************************/ /* see lz4.h LZ4_DISABLE_DEPRECATE_WARNINGS to turn off deprecation warnings */ /* deprecated compression functions */ LZ4_DEPRECATED("use LZ4_compress_HC() instead") LZ4LIB_API int LZ4_compressHC (const char* source, char* dest, int inputSize); LZ4_DEPRECATED("use LZ4_compress_HC() instead") LZ4LIB_API int LZ4_compressHC_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize); LZ4_DEPRECATED("use LZ4_compress_HC() instead") LZ4LIB_API int LZ4_compressHC2 (const char* source, char* dest, int inputSize, int compressionLevel); LZ4_DEPRECATED("use LZ4_compress_HC() instead") LZ4LIB_API int LZ4_compressHC2_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel); LZ4_DEPRECATED("use LZ4_compress_HC_extStateHC() instead") LZ4LIB_API int LZ4_compressHC_withStateHC (void* state, const char* source, char* dest, int inputSize); LZ4_DEPRECATED("use LZ4_compress_HC_extStateHC() instead") LZ4LIB_API int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize); LZ4_DEPRECATED("use LZ4_compress_HC_extStateHC() instead") LZ4LIB_API int LZ4_compressHC2_withStateHC (void* state, const char* source, char* dest, int inputSize, int compressionLevel); LZ4_DEPRECATED("use LZ4_compress_HC_extStateHC() instead") LZ4LIB_API int LZ4_compressHC2_limitedOutput_withStateHC(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel); LZ4_DEPRECATED("use LZ4_compress_HC_continue() instead") LZ4LIB_API int LZ4_compressHC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize); LZ4_DEPRECATED("use LZ4_compress_HC_continue() instead") LZ4LIB_API int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize, int maxOutputSize); /* Obsolete streaming functions; degraded functionality; do not use! * * In order to perform streaming compression, these functions depended on data * that is no longer tracked in the state. They have been preserved as well as * possible: using them will still produce a correct output. However, use of * LZ4_slideInputBufferHC() will truncate the history of the stream, rather * than preserve a window-sized chunk of history. */ LZ4_DEPRECATED("use LZ4_createStreamHC() instead") LZ4LIB_API void* LZ4_createHC (const char* inputBuffer); LZ4_DEPRECATED("use LZ4_saveDictHC() instead") LZ4LIB_API char* LZ4_slideInputBufferHC (void* LZ4HC_Data); LZ4_DEPRECATED("use LZ4_freeStreamHC() instead") LZ4LIB_API int LZ4_freeHC (void* LZ4HC_Data); LZ4_DEPRECATED("use LZ4_compress_HC_continue() instead") LZ4LIB_API int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int compressionLevel); LZ4_DEPRECATED("use LZ4_compress_HC_continue() instead") LZ4LIB_API int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel); LZ4_DEPRECATED("use LZ4_createStreamHC() instead") LZ4LIB_API int LZ4_sizeofStreamStateHC(void); LZ4_DEPRECATED("use LZ4_resetStreamHC() instead") LZ4LIB_API int LZ4_resetStreamStateHC(void* state, char* inputBuffer); #if defined (__cplusplus) } #endif #endif /* LZ4_HC_H_19834876238432 */ /*-************************************************** * !!!!! STATIC LINKING ONLY !!!!! * Following definitions are considered experimental. * They should not be linked from DLL, * as there is no guarantee of API stability yet. * Prototypes will be promoted to "stable" status * after successfull usage in real-life scenarios. ***************************************************/ #ifdef LZ4_HC_STATIC_LINKING_ONLY /* protection macro */ #ifndef LZ4_HC_SLO_098092834 #define LZ4_HC_SLO_098092834 #if defined (__cplusplus) extern "C" { #endif /*! LZ4_compress_HC_destSize() : v1.8.0 (experimental) * Will try to compress as much data from `src` as possible * that can fit into `targetDstSize` budget. * Result is provided in 2 parts : * @return : the number of bytes written into 'dst' * or 0 if compression fails. * `srcSizePtr` : value will be updated to indicate how much bytes were read from `src` */ int LZ4_compress_HC_destSize(void* LZ4HC_Data, const char* src, char* dst, int* srcSizePtr, int targetDstSize, int compressionLevel); /*! LZ4_compress_HC_continue_destSize() : v1.8.0 (experimental) * Similar as LZ4_compress_HC_continue(), * but will read a variable nb of bytes from `src` * to fit into `targetDstSize` budget. * Result is provided in 2 parts : * @return : the number of bytes written into 'dst' * or 0 if compression fails. * `srcSizePtr` : value will be updated to indicate how much bytes were read from `src`. */ int LZ4_compress_HC_continue_destSize(LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int* srcSizePtr, int targetDstSize); /*! LZ4_setCompressionLevel() : v1.8.0 (experimental) * It's possible to change compression level between 2 invocations of LZ4_compress_HC_continue*() */ void LZ4_setCompressionLevel(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel); /*! LZ4_favorDecompressionSpeed() : v1.8.2 (experimental) * Parser will select decisions favoring decompression over compression ratio. * Only work at highest compression settings (level >= LZ4HC_CLEVEL_OPT_MIN) */ void LZ4_favorDecompressionSpeed(LZ4_streamHC_t* LZ4_streamHCPtr, int favor); /*! LZ4_resetStreamHC_fast() : * When an LZ4_streamHC_t is known to be in a internally coherent state, * it can often be prepared for a new compression with almost no work, only * sometimes falling back to the full, expensive reset that is always required * when the stream is in an indeterminate state (i.e., the reset performed by * LZ4_resetStreamHC()). * * LZ4_streamHCs are guaranteed to be in a valid state when: * - returned from LZ4_createStreamHC() * - reset by LZ4_resetStreamHC() * - memset(stream, 0, sizeof(LZ4_streamHC_t)) * - the stream was in a valid state and was reset by LZ4_resetStreamHC_fast() * - the stream was in a valid state and was then used in any compression call * that returned success * - the stream was in an indeterminate state and was used in a compression * call that fully reset the state (LZ4_compress_HC_extStateHC()) and that * returned success */ void LZ4_resetStreamHC_fast(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel); /*! LZ4_compress_HC_extStateHC_fastReset() : * A variant of LZ4_compress_HC_extStateHC(). * * Using this variant avoids an expensive initialization step. It is only safe * to call if the state buffer is known to be correctly initialized already * (see above comment on LZ4_resetStreamHC_fast() for a definition of * "correctly initialized"). From a high level, the difference is that this * function initializes the provided state with a call to * LZ4_resetStreamHC_fast() while LZ4_compress_HC_extStateHC() starts with a * call to LZ4_resetStreamHC(). */ int LZ4_compress_HC_extStateHC_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel); /*! LZ4_attach_HC_dictionary() : * This is an experimental API that allows for the efficient use of a * static dictionary many times. * * Rather than re-loading the dictionary buffer into a working context before * each compression, or copying a pre-loaded dictionary's LZ4_streamHC_t into a * working LZ4_streamHC_t, this function introduces a no-copy setup mechanism, * in which the working stream references the dictionary stream in-place. * * Several assumptions are made about the state of the dictionary stream. * Currently, only streams which have been prepared by LZ4_loadDictHC() should * be expected to work. * * Alternatively, the provided dictionary stream pointer may be NULL, in which * case any existing dictionary stream is unset. * * A dictionary should only be attached to a stream without any history (i.e., * a stream that has just been reset). * * The dictionary will remain attached to the working stream only for the * current stream session. Calls to LZ4_resetStreamHC(_fast) will remove the * dictionary context association from the working stream. The dictionary * stream (and source buffer) must remain in-place / accessible / unchanged * through the lifetime of the stream session. */ LZ4LIB_API void LZ4_attach_HC_dictionary(LZ4_streamHC_t *working_stream, const LZ4_streamHC_t *dictionary_stream); #if defined (__cplusplus) } #endif #endif /* LZ4_HC_SLO_098092834 */ #endif /* LZ4_HC_STATIC_LINKING_ONLY */
17,904
356
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/lz4.h
/* clang-format off */ /* * LZ4 - Fast LZ compression algorithm * Header File * Copyright (C) 2011-present, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) 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. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. You can contact the author at : - LZ4 homepage : http://www.lz4.org - LZ4 source repository : https://github.com/lz4/lz4 */ #if defined (__cplusplus) extern "C" { #endif #ifndef LZ4_H_2983827168210 #define LZ4_H_2983827168210 /* --- Dependency --- */ /** Introduction LZ4 is lossless compression algorithm, providing compression speed at 500 MB/s per core, scalable with multi-cores CPU. It features an extremely fast decoder, with speed in multiple GB/s per core, typically reaching RAM speed limits on multi-core systems. The LZ4 compression library provides in-memory compression and decompression functions. Compression can be done in: - a single step (described as Simple Functions) - a single step, reusing a context (described in Advanced Functions) - unbounded multiple steps (described as Streaming compression) lz4.h provides block compression functions. It gives full buffer control to user. Decompressing an lz4-compressed block also requires metadata (such as compressed size). Each application is free to encode such metadata in whichever way it wants. An additional format, called LZ4 frame specification (doc/lz4_Frame_format.md), take care of encoding standard metadata alongside LZ4-compressed blocks. Frame format is required for interoperability. It is delivered through a companion API, declared in lz4frame.h. */ /*^*************************************************************** * Export parameters *****************************************************************/ /* * LZ4_DLL_EXPORT : * Enable exporting of functions when building a Windows DLL * LZ4LIB_VISIBILITY : * Control library symbols visibility. */ #ifndef LZ4LIB_VISIBILITY # if defined(__GNUC__) && (__GNUC__ >= 4) # define LZ4LIB_VISIBILITY __attribute__ ((visibility ("default"))) # else # define LZ4LIB_VISIBILITY # endif #endif #if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1) # define LZ4LIB_API __declspec(dllexport) LZ4LIB_VISIBILITY #elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1) # define LZ4LIB_API __declspec(dllimport) LZ4LIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ #else # define LZ4LIB_API LZ4LIB_VISIBILITY #endif /*------ Version ------*/ #define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */ #define LZ4_VERSION_MINOR 8 /* for new (non-breaking) interface capabilities */ #define LZ4_VERSION_RELEASE 3 /* for tweaks, bug-fixes, or development */ #define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE) #define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE #define LZ4_QUOTE(str) #str #define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str) #define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION) LZ4LIB_API int LZ4_versionNumber (void); /**< library version number; useful to check dll version */ LZ4LIB_API const char* LZ4_versionString (void); /**< library version string; unseful to check dll version */ /*-************************************ * Tuning parameter **************************************/ /*! * LZ4_MEMORY_USAGE : * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) * Increasing memory usage improves compression ratio * Reduced memory usage may improve speed, thanks to cache effect * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ #ifndef LZ4_MEMORY_USAGE # define LZ4_MEMORY_USAGE 14 #endif /*-************************************ * Simple Functions **************************************/ /*! LZ4_compress_default() : Compresses 'srcSize' bytes from buffer 'src' into already allocated 'dst' buffer of size 'dstCapacity'. Compression is guaranteed to succeed if 'dstCapacity' >= LZ4_compressBound(srcSize). It also runs faster, so it's a recommended setting. If the function cannot compress 'src' into a more limited 'dst' budget, compression stops *immediately*, and the function result is zero. Note : as a consequence, 'dst' content is not valid. Note 2 : This function is protected against buffer overflow scenarios (never writes outside 'dst' buffer, nor read outside 'source' buffer). srcSize : max supported value is LZ4_MAX_INPUT_SIZE. dstCapacity : size of buffer 'dst' (which must be already allocated) return : the number of bytes written into buffer 'dst' (necessarily <= dstCapacity) or 0 if compression fails */ LZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity); /*! LZ4_decompress_safe() : compressedSize : is the exact complete size of the compressed block. dstCapacity : is the size of destination buffer, which must be already allocated. return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity) If destination buffer is not large enough, decoding will stop and output an error code (negative value). If the source stream is detected malformed, the function will stop decoding and return a negative result. This function is protected against malicious data packets. */ LZ4LIB_API int LZ4_decompress_safe (const char* src, char* dst, int compressedSize, int dstCapacity); /*-************************************ * Advanced Functions **************************************/ #define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ #define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16) /*! LZ4_compressBound() : Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible) This function is primarily useful for memory allocation purposes (destination buffer size). Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example). Note that LZ4_compress_default() compresses faster when dstCapacity is >= LZ4_compressBound(srcSize) inputSize : max supported value is LZ4_MAX_INPUT_SIZE return : maximum output size in a "worst case" scenario or 0, if input size is incorrect (too large or negative) */ LZ4LIB_API int LZ4_compressBound(int inputSize); /*! LZ4_compress_fast() : Same as LZ4_compress_default(), but allows selection of "acceleration" factor. The larger the acceleration value, the faster the algorithm, but also the lesser the compression. It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed. An acceleration value of "1" is the same as regular LZ4_compress_default() Values <= 0 will be replaced by ACCELERATION_DEFAULT (currently == 1, see lz4.c). */ LZ4LIB_API int LZ4_compress_fast (const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); /*! LZ4_compress_fast_extState() : Same compression function, just using an externally allocated memory space to store compression state. Use LZ4_sizeofState() to know how much memory must be allocated, and allocate it on 8-bytes boundaries (using malloc() typically). Then, provide this buffer as 'void* state' to compression function. */ LZ4LIB_API int LZ4_sizeofState(void); LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); /*! LZ4_compress_destSize() : * Reverse the logic : compresses as much data as possible from 'src' buffer * into already allocated buffer 'dst', of size >= 'targetDestSize'. * This function either compresses the entire 'src' content into 'dst' if it's large enough, * or fill 'dst' buffer completely with as much data as possible from 'src'. * note: acceleration parameter is fixed to "default". * * *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'. * New value is necessarily <= input value. * @return : Nb bytes written into 'dst' (necessarily <= targetDestSize) * or 0 if compression fails. */ LZ4LIB_API int LZ4_compress_destSize (const char* src, char* dst, int* srcSizePtr, int targetDstSize); /*! LZ4_decompress_fast() : **unsafe!** * This function used to be a bit faster than LZ4_decompress_safe(), * though situation has changed in recent versions, * and now `LZ4_decompress_safe()` can be as fast and sometimes faster than `LZ4_decompress_fast()`. * Moreover, LZ4_decompress_fast() is not protected vs malformed input, as it doesn't perform full validation of compressed data. * As a consequence, this function is no longer recommended, and may be deprecated in future versions. * It's only remaining specificity is that it can decompress data without knowing its compressed size. * * originalSize : is the uncompressed size to regenerate. * `dst` must be already allocated, its size must be >= 'originalSize' bytes. * @return : number of bytes read from source buffer (== compressed size). * If the source stream is detected malformed, the function stops decoding and returns a negative result. * note : This function requires uncompressed originalSize to be known in advance. * The function never writes past the output buffer. * However, since it doesn't know its 'src' size, it may read past the intended input. * Also, because match offsets are not validated during decoding, * reads from 'src' may underflow. * Use this function in trusted environment **only**. */ LZ4LIB_API int LZ4_decompress_fast (const char* src, char* dst, int originalSize); /*! LZ4_decompress_safe_partial() : * Decompress an LZ4 compressed block, of size 'srcSize' at position 'src', * into destination buffer 'dst' of size 'dstCapacity'. * Up to 'targetOutputSize' bytes will be decoded. * The function stops decoding on reaching this objective, * which can boost performance when only the beginning of a block is required. * * @return : the number of bytes decoded in `dst` (necessarily <= dstCapacity) * If source stream is detected malformed, function returns a negative result. * * Note : @return can be < targetOutputSize, if compressed block contains less data. * * Note 2 : this function features 2 parameters, targetOutputSize and dstCapacity, * and expects targetOutputSize <= dstCapacity. * It effectively stops decoding on reaching targetOutputSize, * so dstCapacity is kind of redundant. * This is because in a previous version of this function, * decoding operation would not "break" a sequence in the middle. * As a consequence, there was no guarantee that decoding would stop at exactly targetOutputSize, * it could write more bytes, though only up to dstCapacity. * Some "margin" used to be required for this operation to work properly. * This is no longer necessary. * The function nonetheless keeps its signature, in an effort to not break API. */ LZ4LIB_API int LZ4_decompress_safe_partial (const char* src, char* dst, int srcSize, int targetOutputSize, int dstCapacity); /*-********************************************* * Streaming Compression Functions ***********************************************/ typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */ /*! LZ4_createStream() and LZ4_freeStream() : * LZ4_createStream() will allocate and initialize an `LZ4_stream_t` structure. * LZ4_freeStream() releases its memory. */ LZ4LIB_API LZ4_stream_t* LZ4_createStream(void); LZ4LIB_API int LZ4_freeStream (LZ4_stream_t* streamPtr); /*! LZ4_resetStream() : * An LZ4_stream_t structure can be allocated once and re-used multiple times. * Use this function to start compressing a new stream. */ LZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr); /*! LZ4_loadDict() : * Use this function to load a static dictionary into LZ4_stream_t. * Any previous data will be forgotten, only 'dictionary' will remain in memory. * Loading a size of 0 is allowed, and is the same as reset. * @return : dictionary size, in bytes (necessarily <= 64 KB) */ LZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize); /*! LZ4_compress_fast_continue() : * Compress 'src' content using data from previously compressed blocks, for better compression ratio. * 'dst' buffer must be already allocated. * If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster. * * @return : size of compressed block * or 0 if there is an error (typically, cannot fit into 'dst'). * * Note 1 : Each invocation to LZ4_compress_fast_continue() generates a new block. * Each block has precise boundaries. * It's not possible to append blocks together and expect a single invocation of LZ4_decompress_*() to decompress them together. * Each block must be decompressed separately, calling LZ4_decompress_*() with associated metadata. * * Note 2 : The previous 64KB of source data is __assumed__ to remain present, unmodified, at same address in memory! * * Note 3 : When input is structured as a double-buffer, each buffer can have any size, including < 64 KB. * Make sure that buffers are separated, by at least one byte. * This construction ensures that each block only depends on previous block. * * Note 4 : If input buffer is a ring-buffer, it can have any size, including < 64 KB. * * Note 5 : After an error, the stream status is invalid, it can only be reset or freed. */ LZ4LIB_API int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); /*! LZ4_saveDict() : * If last 64KB data cannot be guaranteed to remain available at its current memory location, * save it into a safer place (char* safeBuffer). * This is schematically equivalent to a memcpy() followed by LZ4_loadDict(), * but is much faster, because LZ4_saveDict() doesn't need to rebuild tables. * @return : saved dictionary size in bytes (necessarily <= maxDictSize), or 0 if error. */ LZ4LIB_API int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int maxDictSize); /*-********************************************** * Streaming Decompression Functions * Bufferless synchronous API ************************************************/ typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* tracking context */ /*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() : * creation / destruction of streaming decompression tracking context. * A tracking context can be re-used multiple times. */ LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void); LZ4LIB_API int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream); /*! LZ4_setStreamDecode() : * An LZ4_streamDecode_t context can be allocated once and re-used multiple times. * Use this function to start decompression of a new stream of blocks. * A dictionary can optionally be set. Use NULL or size 0 for a reset order. * Dictionary is presumed stable : it must remain accessible and unmodified during next decompression. * @return : 1 if OK, 0 if error */ LZ4LIB_API int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize); /*! LZ4_decoderRingBufferSize() : v1.8.2 * Note : in a ring buffer scenario (optional), * blocks are presumed decompressed next to each other * up to the moment there is not enough remaining space for next block (remainingSize < maxBlockSize), * at which stage it resumes from beginning of ring buffer. * When setting such a ring buffer for streaming decompression, * provides the minimum size of this ring buffer * to be compatible with any source respecting maxBlockSize condition. * @return : minimum ring buffer size, * or 0 if there is an error (invalid maxBlockSize). */ LZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize); #define LZ4_DECODER_RING_BUFFER_SIZE(mbs) (65536 + 14 + (mbs)) /* for static allocation; mbs presumed valid */ /*! LZ4_decompress_*_continue() : * These decoding functions allow decompression of consecutive blocks in "streaming" mode. * A block is an unsplittable entity, it must be presented entirely to a decompression function. * Decompression functions only accepts one block at a time. * The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded. * If less than 64KB of data has been decoded, all the data must be present. * * Special : if decompression side sets a ring buffer, it must respect one of the following conditions : * - Decompression buffer size is _at least_ LZ4_decoderRingBufferSize(maxBlockSize). * maxBlockSize is the maximum size of any single block. It can have any value > 16 bytes. * In which case, encoding and decoding buffers do not need to be synchronized. * Actually, data can be produced by any source compliant with LZ4 format specification, and respecting maxBlockSize. * - Synchronized mode : * Decompression buffer size is _exactly_ the same as compression buffer size, * and follows exactly same update rule (block boundaries at same positions), * and decoding function is provided with exact decompressed size of each block (exception for last block of the stream), * _then_ decoding & encoding ring buffer can have any size, including small ones ( < 64 KB). * - Decompression buffer is larger than encoding buffer, by a minimum of maxBlockSize more bytes. * In which case, encoding and decoding buffers do not need to be synchronized, * and encoding ring buffer can have any size, including small ones ( < 64 KB). * * Whenever these conditions are not possible, * save the last 64KB of decoded data into a safe buffer where it can't be modified during decompression, * then indicate where this data is saved using LZ4_setStreamDecode(), before decompressing next block. */ LZ4LIB_API int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int srcSize, int dstCapacity); LZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize); /*! LZ4_decompress_*_usingDict() : * These decoding functions work the same as * a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue() * They are stand-alone, and don't need an LZ4_streamDecode_t structure. * Dictionary is presumed stable : it must remain accessible and unmodified during next decompression. */ LZ4LIB_API int LZ4_decompress_safe_usingDict (const char* src, char* dst, int srcSize, int dstCapcity, const char* dictStart, int dictSize); LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize); /*^********************************************** * !!!!!! STATIC LINKING ONLY !!!!!! ***********************************************/ /*-************************************ * Unstable declarations ************************************** * Declarations in this section should be considered unstable. * Use at your own peril, etc., etc. * They may be removed in the future. * Their signatures may change. **************************************/ #ifdef LZ4_STATIC_LINKING_ONLY /*! LZ4_resetStream_fast() : * Use this, like LZ4_resetStream(), to prepare a context for a new chain of * calls to a streaming API (e.g., LZ4_compress_fast_continue()). * * Note: * Using this in advance of a non- streaming-compression function is redundant, * and potentially bad for performance, since they all perform their own custom * reset internally. * * Differences from LZ4_resetStream(): * When an LZ4_stream_t is known to be in a internally coherent state, * it can often be prepared for a new compression with almost no work, only * sometimes falling back to the full, expensive reset that is always required * when the stream is in an indeterminate state (i.e., the reset performed by * LZ4_resetStream()). * * LZ4_streams are guaranteed to be in a valid state when: * - returned from LZ4_createStream() * - reset by LZ4_resetStream() * - memset(stream, 0, sizeof(LZ4_stream_t)), though this is discouraged * - the stream was in a valid state and was reset by LZ4_resetStream_fast() * - the stream was in a valid state and was then used in any compression call * that returned success * - the stream was in an indeterminate state and was used in a compression * call that fully reset the state (e.g., LZ4_compress_fast_extState()) and * that returned success * * When a stream isn't known to be in a valid state, it is not safe to pass to * any fastReset or streaming function. It must first be cleansed by the full * LZ4_resetStream(). */ LZ4LIB_API void LZ4_resetStream_fast (LZ4_stream_t* streamPtr); /*! LZ4_compress_fast_extState_fastReset() : * A variant of LZ4_compress_fast_extState(). * * Using this variant avoids an expensive initialization step. It is only safe * to call if the state buffer is known to be correctly initialized already * (see above comment on LZ4_resetStream_fast() for a definition of "correctly * initialized"). From a high level, the difference is that this function * initializes the provided state with a call to something like * LZ4_resetStream_fast() while LZ4_compress_fast_extState() starts with a * call to LZ4_resetStream(). */ LZ4LIB_API int LZ4_compress_fast_extState_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); /*! LZ4_attach_dictionary() : * This is an experimental API that allows for the efficient use of a * static dictionary many times. * * Rather than re-loading the dictionary buffer into a working context before * each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a * working LZ4_stream_t, this function introduces a no-copy setup mechanism, * in which the working stream references the dictionary stream in-place. * * Several assumptions are made about the state of the dictionary stream. * Currently, only streams which have been prepared by LZ4_loadDict() should * be expected to work. * * Alternatively, the provided dictionary stream pointer may be NULL, in which * case any existing dictionary stream is unset. * * If a dictionary is provided, it replaces any pre-existing stream history. * The dictionary contents are the only history that can be referenced and * logically immediately precede the data compressed in the first subsequent * compression call. * * The dictionary will only remain attached to the working stream through the * first compression call, at the end of which it is cleared. The dictionary * stream (and source buffer) must remain in-place / accessible / unchanged * through the completion of the first compression call on the stream. */ LZ4LIB_API void LZ4_attach_dictionary(LZ4_stream_t *working_stream, const LZ4_stream_t *dictionary_stream); #endif /*-************************************ * Private definitions ************************************** * Do not use these definitions. * They are exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`. * Using these definitions will expose code to API and/or ABI break in future versions of the library. **************************************/ #define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2) #define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE) #define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */ #if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) typedef struct LZ4_stream_t_internal LZ4_stream_t_internal; struct LZ4_stream_t_internal { uint32_t hashTable[LZ4_HASH_SIZE_U32]; uint32_t currentOffset; uint16_t initCheck; uint16_t tableType; const uint8_t* dictionary; const LZ4_stream_t_internal* dictCtx; uint32_t dictSize; }; typedef struct { const uint8_t* externalDict; size_t extDictSize; const uint8_t* prefixEnd; size_t prefixSize; } LZ4_streamDecode_t_internal; #else typedef struct LZ4_stream_t_internal LZ4_stream_t_internal; struct LZ4_stream_t_internal { unsigned int hashTable[LZ4_HASH_SIZE_U32]; unsigned int currentOffset; unsigned short initCheck; unsigned short tableType; const unsigned char* dictionary; const LZ4_stream_t_internal* dictCtx; unsigned int dictSize; }; typedef struct { const unsigned char* externalDict; size_t extDictSize; const unsigned char* prefixEnd; size_t prefixSize; } LZ4_streamDecode_t_internal; #endif /*! * LZ4_stream_t : * information structure to track an LZ4 stream. * init this structure before first use. * note : only use in association with static linking ! * this definition is not API/ABI safe, * it may change in a future version ! */ #define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4) #define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(unsigned long long)) union LZ4_stream_u { unsigned long long table[LZ4_STREAMSIZE_U64]; LZ4_stream_t_internal internal_donotuse; } ; /* previously typedef'd to LZ4_stream_t */ /*! * LZ4_streamDecode_t : * information structure to track an LZ4 stream during decompression. * init this structure using LZ4_setStreamDecode (or memset()) before first use * note : only use in association with static linking ! * this definition is not API/ABI safe, * and may change in a future version ! */ #define LZ4_STREAMDECODESIZE_U64 4 #define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long)) union LZ4_streamDecode_u { unsigned long long table[LZ4_STREAMDECODESIZE_U64]; LZ4_streamDecode_t_internal internal_donotuse; } ; /* previously typedef'd to LZ4_streamDecode_t */ /*-************************************ * Obsolete Functions **************************************/ /*! Deprecation warnings Should deprecation warnings be a problem, it is generally possible to disable them, typically with -Wno-deprecated-declarations for gcc or _CRT_SECURE_NO_WARNINGS in Visual. Otherwise, it's also possible to define LZ4_DISABLE_DEPRECATE_WARNINGS */ #ifdef LZ4_DISABLE_DEPRECATE_WARNINGS # define LZ4_DEPRECATED(message) /* disable deprecation warnings */ #else # define LZ4_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) # if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ # define LZ4_DEPRECATED(message) [[deprecated(message)]] # elif (LZ4_GCC_VERSION >= 405) || defined(__clang__) # define LZ4_DEPRECATED(message) __attribute__((deprecated(message))) # elif (LZ4_GCC_VERSION >= 301) # define LZ4_DEPRECATED(message) __attribute__((deprecated)) # elif defined(_MSC_VER) # define LZ4_DEPRECATED(message) __declspec(deprecated(message)) # else # pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler") # define LZ4_DEPRECATED(message) # endif #endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */ /* Obsolete compression functions */ LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress (const char* source, char* dest, int sourceSize); LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize); LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize); LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize); LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize); LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize); /* Obsolete decompression functions */ LZ4_DEPRECATED("use LZ4_decompress_fast() instead") LZ4LIB_API int LZ4_uncompress (const char* source, char* dest, int outputSize); LZ4_DEPRECATED("use LZ4_decompress_safe() instead") LZ4LIB_API int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); /* Obsolete streaming functions; degraded functionality; do not use! * * In order to perform streaming compression, these functions depended on data * that is no longer tracked in the state. They have been preserved as well as * possible: using them will still produce a correct output. However, they don't * actually retain any history between compression calls. The compression ratio * achieved will therefore be no better than compressing each chunk * independently. */ LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API void* LZ4_create (char* inputBuffer); LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API int LZ4_sizeofStreamState(void); LZ4_DEPRECATED("Use LZ4_resetStream() instead") LZ4LIB_API int LZ4_resetStreamState(void* state, char* inputBuffer); LZ4_DEPRECATED("Use LZ4_saveDict() instead") LZ4LIB_API char* LZ4_slideInputBuffer (void* state); /* Obsolete streaming decoding functions */ LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") LZ4LIB_API int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize); LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize); #endif /* LZ4_H_2983827168210 */ #if defined (__cplusplus) } #endif
31,829
631
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/xxhash.h
/* clang-format off */ /* xxHash - Extremely Fast Hash algorithm Header File Copyright (C) 2012-2016, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) 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. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. You can contact the author at : - xxHash source repository : https://github.com/Cyan4973/xxHash */ /* Notice extracted from xxHash homepage : xxHash is an extremely fast Hash algorithm, running at RAM speed limits. It also successfully passes all tests from the SMHasher suite. Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz) Name Speed Q.Score Author xxHash 5.4 GB/s 10 CrapWow 3.2 GB/s 2 Andrew MumurHash 3a 2.7 GB/s 10 Austin Appleby SpookyHash 2.0 GB/s 10 Bob Jenkins SBox 1.4 GB/s 9 Bret Mulvey Lookup3 1.2 GB/s 9 Bob Jenkins SuperFastHash 1.2 GB/s 1 Paul Hsieh CityHash64 1.05 GB/s 10 Pike & Alakuijala FNV 0.55 GB/s 5 Fowler, Noll, Vo CRC32 0.43 GB/s 9 MD5-32 0.33 GB/s 10 Ronald L. Rivest SHA1-32 0.28 GB/s 10 Q.Score is a measure of quality of the hash function. It depends on successfully passing SMHasher test set. 10 is a perfect score. A 64-bits version, named XXH64, is available since r35. It offers much better speed, but for 64-bits applications only. Name Speed on 64 bits Speed on 32 bits XXH64 13.8 GB/s 1.9 GB/s XXH32 6.8 GB/s 6.0 GB/s */ #ifndef XXHASH_H_5627135585666179 #define XXHASH_H_5627135585666179 1 #if defined (__cplusplus) extern "C" { #endif /* **************************** * Definitions ******************************/ typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode; /* **************************** * API modifier ******************************/ /** XXH_PRIVATE_API * This is useful to include xxhash functions in `static` mode * in order to inline them, and remove their symbol from the public list. * Methodology : * #define XXH_PRIVATE_API * #include "xxhash.h" * `xxhash.c` is automatically included. * It's not useful to compile and link it as a separate module. */ #ifdef XXH_PRIVATE_API # ifndef XXH_STATIC_LINKING_ONLY # define XXH_STATIC_LINKING_ONLY # endif # if defined(__GNUC__) # define XXH_PUBLIC_API static __inline __attribute__((unused)) # elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) # define XXH_PUBLIC_API static inline # elif defined(_MSC_VER) # define XXH_PUBLIC_API static __inline # else # define XXH_PUBLIC_API static /* this version may generate warnings for unused static functions; disable the relevant warning */ # endif #else # define XXH_PUBLIC_API /* do nothing */ #endif /* XXH_PRIVATE_API */ /*!XXH_NAMESPACE, aka Namespace Emulation : If you want to include _and expose_ xxHash functions from within your own library, but also want to avoid symbol collisions with other libraries which may also include xxHash, you can use XXH_NAMESPACE, to automatically prefix any public symbol from xxhash library with the value of XXH_NAMESPACE (therefore, avoid NULL and numeric values). Note that no change is required within the calling program as long as it includes `xxhash.h` : regular symbol name will be automatically translated by this header. */ #ifdef XXH_NAMESPACE # define XXH_CAT(A,B) A##B # define XXH_NAME2(A,B) XXH_CAT(A,B) # define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber) # define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32) # define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState) # define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState) # define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset) # define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update) # define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest) # define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState) # define XXH32_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH32_canonicalFromHash) # define XXH32_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH32_hashFromCanonical) # define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64) # define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState) # define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState) # define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset) # define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update) # define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest) # define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState) # define XXH64_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH64_canonicalFromHash) # define XXH64_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH64_hashFromCanonical) #endif /* ************************************* * Version ***************************************/ #define XXH_VERSION_MAJOR 0 #define XXH_VERSION_MINOR 6 #define XXH_VERSION_RELEASE 2 #define XXH_VERSION_NUMBER (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE) XXH_PUBLIC_API unsigned XXH_versionNumber (void); /*-********************************************************************** * 32-bits hash ************************************************************************/ typedef unsigned int XXH32_hash_t; /*! XXH32() : Calculate the 32-bits hash of sequence "length" bytes stored at memory address "input". The memory between input & input+length must be valid (allocated and read-accessible). "seed" can be used to alter the result predictably. Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s */ XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t length, unsigned int seed); /*====== Streaming ======*/ typedef struct XXH32_state_s XXH32_state_t; /* incomplete type */ XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void); XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr); XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dst_state, const XXH32_state_t* src_state); XXH_PUBLIC_API XXH_errorcode XXH32_reset (XXH32_state_t* statePtr, unsigned int seed); XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length); XXH_PUBLIC_API XXH32_hash_t XXH32_digest (const XXH32_state_t* statePtr); /* These functions generate the xxHash of an input provided in multiple segments. Note that, for small input, they are slower than single-call functions, due to state management. For small input, prefer `XXH32()` and `XXH64()` . XXH state must first be allocated, using XXH*_createState() . Start a new hash by initializing state with a seed, using XXH*_reset(). Then, feed the hash state by calling XXH*_update() as many times as necessary. Obviously, input must be allocated and read accessible. The function returns an error code, with 0 meaning OK, and any other value meaning there is an error. Finally, a hash value can be produced anytime, by using XXH*_digest(). This function returns the nn-bits hash as an int or long long. It's still possible to continue inserting input into the hash state after a digest, and generate some new hashes later on, by calling again XXH*_digest(). When done, free XXH state space if it was allocated dynamically. */ /*====== Canonical representation ======*/ typedef struct { unsigned char digest[4]; } XXH32_canonical_t; XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash); XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src); /* Default result type for XXH functions are primitive unsigned 32 and 64 bits. * The canonical representation uses human-readable write convention, aka big-endian (large digits first). * These functions allow transformation of hash result into and from its canonical format. * This way, hash values can be written into a file / memory, and remain comparable on different systems and programs. */ #ifndef XXH_NO_LONG_LONG /*-********************************************************************** * 64-bits hash ************************************************************************/ typedef unsigned long long XXH64_hash_t; /*! XXH64() : Calculate the 64-bits hash of sequence of length "len" stored at memory address "input". "seed" can be used to alter the result predictably. This function runs faster on 64-bits systems, but slower on 32-bits systems (see benchmark). */ XXH_PUBLIC_API XXH64_hash_t XXH64 (const void* input, size_t length, unsigned long long seed); /*====== Streaming ======*/ typedef struct XXH64_state_s XXH64_state_t; /* incomplete type */ XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void); XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr); XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dst_state, const XXH64_state_t* src_state); XXH_PUBLIC_API XXH_errorcode XXH64_reset (XXH64_state_t* statePtr, unsigned long long seed); XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length); XXH_PUBLIC_API XXH64_hash_t XXH64_digest (const XXH64_state_t* statePtr); /*====== Canonical representation ======*/ typedef struct { unsigned char digest[8]; } XXH64_canonical_t; XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash); XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src); #endif /* XXH_NO_LONG_LONG */ #ifdef XXH_STATIC_LINKING_ONLY /* ================================================================================================ This section contains definitions which are not guaranteed to remain stable. They may change in future versions, becoming incompatible with a different version of the library. They shall only be used with static linking. Never use these definitions in association with dynamic linking ! =================================================================================================== */ /* These definitions are only meant to allow allocation of XXH state statically, on stack, or in a struct for example. Do not use members directly. */ struct XXH32_state_s { unsigned total_len_32; unsigned large_len; unsigned v1; unsigned v2; unsigned v3; unsigned v4; unsigned mem32[4]; /* buffer defined as U32 for alignment */ unsigned memsize; unsigned reserved; /* never read nor write, will be removed in a future version */ }; /* typedef'd to XXH32_state_t */ #ifndef XXH_NO_LONG_LONG struct XXH64_state_s { unsigned long long total_len; unsigned long long v1; unsigned long long v2; unsigned long long v3; unsigned long long v4; unsigned long long mem64[4]; /* buffer defined as U64 for alignment */ unsigned memsize; unsigned reserved[2]; /* never read nor write, will be removed in a future version */ }; /* typedef'd to XXH64_state_t */ #endif # ifdef XXH_PRIVATE_API # include "third_party/lz4cli/xxhash.c" /* include xxhash function bodies as `static`, for inlining */ # endif #endif /* XXH_STATIC_LINKING_ONLY */ #if defined (__cplusplus) } #endif #endif /* XXHASH_H_5627135585666179 */
12,643
294
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/lz4.c
/* clang-format off */ /* LZ4 - Fast LZ compression algorithm Copyright (C) 2011-present, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) 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. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. You can contact the author at : - LZ4 homepage : http://www.lz4.org - LZ4 source repository : https://github.com/lz4/lz4 */ /*-************************************ * Tuning parameters **************************************/ /* * LZ4_HEAPMODE : * Select how default compression functions will allocate memory for their hash table, * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()). */ #ifndef LZ4_HEAPMODE # define LZ4_HEAPMODE 0 #endif /* * ACCELERATION_DEFAULT : * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0 */ #define ACCELERATION_DEFAULT 1 /*-************************************ * CPU Feature Detection **************************************/ /* LZ4_FORCE_MEMORY_ACCESS * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. * The below switch allow to select different access method for improved performance. * Method 0 (default) : use `memcpy()`. Safe and portable. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. * Method 2 : direct access. This method is portable but violate C standard. * It can generate buggy code on targets which assembly generation depends on alignment. * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details. * Prefer these methods in priority order (0 > 1 > 2) */ #ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */ # if defined(__GNUC__) && \ ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \ || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) # define LZ4_FORCE_MEMORY_ACCESS 2 # elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__) # define LZ4_FORCE_MEMORY_ACCESS 1 # endif #endif /* * LZ4_FORCE_SW_BITCOUNT * Define this parameter if your target system or compiler does not support hardware bit count */ #if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for WinCE doesn't support Hardware bit count */ # define LZ4_FORCE_SW_BITCOUNT #endif /*-************************************ * Dependency **************************************/ #define LZ4_STATIC_LINKING_ONLY #define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */ #include "libc/assert.h" #include "third_party/lz4cli/lz4.h" /* see also "memory routines" below */ /*-************************************ * Compiler Options **************************************/ #ifdef _MSC_VER /* Visual Studio */ # include <intrin.h> # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ # pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */ #endif /* _MSC_VER */ #define LZ4_FORCE_INLINE static inline /* LZ4_FORCE_O2_GCC_PPC64LE and LZ4_FORCE_O2_INLINE_GCC_PPC64LE * Gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy, * together with a simple 8-byte copy loop as a fall-back path. * However, this optimization hurts the decompression speed by >30%, * because the execution does not go to the optimized loop * for typical compressible data, and all of the preamble checks * before going to the fall-back path become useless overhead. * This optimization happens only with the -O3 flag, and -O2 generates * a simple 8-byte copy loop. * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy * functions are annotated with __attribute__((optimize("O2"))), * and also LZ4_wildCopy is forcibly inlined, so that the O2 attribute * of LZ4_wildCopy does not affect the compression speed. */ #if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) # define LZ4_FORCE_O2_GCC_PPC64LE __attribute__((optimize("O2"))) # define LZ4_FORCE_O2_INLINE_GCC_PPC64LE __attribute__((optimize("O2"))) LZ4_FORCE_INLINE #else # define LZ4_FORCE_O2_GCC_PPC64LE # define LZ4_FORCE_O2_INLINE_GCC_PPC64LE static #endif #if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__) # define expect(expr,value) (__builtin_expect ((expr),(value)) ) #else # define expect(expr,value) (expr) #endif #ifndef likely #define likely(expr) expect((expr) != 0, 1) #endif #ifndef unlikely #define unlikely(expr) expect((expr) != 0, 0) #endif /*-************************************ * Memory routines **************************************/ #include "libc/mem/mem.h" #define ALLOC(s) malloc(s) #define ALLOC_AND_ZERO(s) calloc(1,s) #define FREEMEM(p) free(p) #include "libc/str/str.h" #define MEM_INIT(p,v,s) memset((p),(v),(s)) /*-************************************ * Basic Types **************************************/ #if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) typedef uint8_t BYTE; typedef uint16_t U16; typedef uint32_t U32; typedef int32_t S32; typedef uint64_t U64; typedef uintptr_t uptrval; #else typedef unsigned char BYTE; typedef unsigned short U16; typedef unsigned int U32; typedef signed int S32; typedef unsigned long long U64; typedef size_t uptrval; /* generally true, except OpenVMS-64 */ #endif #if defined(__x86_64__) typedef U64 reg_t; /* 64-bits in x32 mode */ #else typedef size_t reg_t; /* 32-bits in x32 mode */ #endif /*-************************************ * Reading and writing into memory **************************************/ static unsigned LZ4_isLittleEndian(void) { const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ return one.c[0]; } #if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2) /* lie to the compiler about data alignment; use with caution */ static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; } static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; } static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; } static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; } static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } #elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1) /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ /* currently only defined for gcc and icc */ typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign; static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; } static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; } static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; } static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; } #else /* safe and portable access through memcpy() */ static U16 LZ4_read16(const void* memPtr) { U16 val; memcpy(&val, memPtr, sizeof(val)); return val; } static U32 LZ4_read32(const void* memPtr) { U32 val; memcpy(&val, memPtr, sizeof(val)); return val; } static reg_t LZ4_read_ARCH(const void* memPtr) { reg_t val; memcpy(&val, memPtr, sizeof(val)); return val; } static void LZ4_write16(void* memPtr, U16 value) { memcpy(memPtr, &value, sizeof(value)); } static void LZ4_write32(void* memPtr, U32 value) { memcpy(memPtr, &value, sizeof(value)); } #endif /* LZ4_FORCE_MEMORY_ACCESS */ static U16 LZ4_readLE16(const void* memPtr) { if (LZ4_isLittleEndian()) { return LZ4_read16(memPtr); } else { const BYTE* p = (const BYTE*)memPtr; return (U16)((U16)p[0] + (p[1]<<8)); } } static void LZ4_writeLE16(void* memPtr, U16 value) { if (LZ4_isLittleEndian()) { LZ4_write16(memPtr, value); } else { BYTE* p = (BYTE*)memPtr; p[0] = (BYTE) value; p[1] = (BYTE)(value>>8); } } /* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */ LZ4_FORCE_O2_INLINE_GCC_PPC64LE void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd) { BYTE* d = (BYTE*)dstPtr; const BYTE* s = (const BYTE*)srcPtr; BYTE* const e = (BYTE*)dstEnd; do { memcpy(d,s,8); d+=8; s+=8; } while (d<e); } /*-************************************ * Common Constants **************************************/ #define MINMATCH 4 #define WILDCOPYLENGTH 8 #define LASTLITERALS 5 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ #define MFLIMIT 12 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ #define MATCH_SAFEGUARD_DISTANCE ((2*WILDCOPYLENGTH) - MINMATCH) /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */ static const int LZ4_minLength = (MFLIMIT+1); #define KB *(1 <<10) #define MB *(1 <<20) #define GB *(1U<<30) #define MAXD_LOG 16 #define MAX_DISTANCE ((1 << MAXD_LOG) - 1) #define ML_BITS 4 #define ML_MASK ((1U<<ML_BITS)-1) #define RUN_BITS (8-ML_BITS) #define RUN_MASK ((1U<<RUN_BITS)-1) /*-************************************ * Error detection **************************************/ #if defined(LZ4_DEBUG) && (LZ4_DEBUG>=1) #include "libc/runtime/runtime.h" #endif #define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use after variable declarations */ #if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2) #include "libc/stdio/stdio.h" static int g_debuglog_enable = 1; # define DEBUGLOG(l, ...) { \ if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) { \ fprintf(stderr, __FILE__ ": "); \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, " \n"); \ } } #else # define DEBUGLOG(l, ...) {} /* disabled */ #endif /*-************************************ * Common functions **************************************/ static unsigned LZ4_NbCommonBytes (reg_t val) { if (LZ4_isLittleEndian()) { if (sizeof(val)==8) { # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) unsigned long r = 0; _BitScanForward64( &r, (U64)val ); return (int)(r>>3); # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) return (__builtin_ctzll((U64)val) >> 3); # else static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 }; return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58]; # endif } else /* 32 bits */ { # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) unsigned long r; _BitScanForward( &r, (U32)val ); return (int)(r>>3); # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) return (__builtin_ctz((U32)val) >> 3); # else static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27]; # endif } } else /* Big Endian CPU */ { if (sizeof(val)==8) { /* 64-bits */ # if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) unsigned long r = 0; _BitScanReverse64( &r, val ); return (unsigned)(r>>3); # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) return (__builtin_clzll((U64)val) >> 3); # else static const U32 by32 = sizeof(val)*4; /* 32 on 64 bits (goal), 16 on 32 bits. Just to avoid some static analyzer complaining about shift by 32 on 32-bits target. Note that this code path is never triggered in 32-bits mode. */ unsigned r; if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; } if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } r += (!val); return r; # endif } else /* 32 bits */ { # if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) unsigned long r = 0; _BitScanReverse( &r, (unsigned long)val ); return (unsigned)(r>>3); # elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT) return (__builtin_clz((U32)val) >> 3); # else unsigned r; if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; } r += (!val); return r; # endif } } } #define STEPSIZE sizeof(reg_t) LZ4_FORCE_INLINE unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) { const BYTE* const pStart = pIn; if (likely(pIn < pInLimit-(STEPSIZE-1))) { reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; } else { return LZ4_NbCommonBytes(diff); } } while (likely(pIn < pInLimit-(STEPSIZE-1))) { reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn); if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; } pIn += LZ4_NbCommonBytes(diff); return (unsigned)(pIn - pStart); } if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; } if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; } if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++; return (unsigned)(pIn - pStart); } #ifndef LZ4_COMMONDEFS_ONLY /*-************************************ * Local Constants **************************************/ static const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1)); static const U32 LZ4_skipTrigger = 6; /* Increase this value ==> compression run slower on incompressible data */ /*-************************************ * Local Structures and types **************************************/ typedef enum { notLimited = 0, limitedOutput = 1, fillOutput = 2 } limitedOutput_directive; typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t; /** * This enum distinguishes several different modes of accessing previous * content in the stream. * * - noDict : There is no preceding content. * - withPrefix64k : Table entries up to ctx->dictSize before the current blob * blob being compressed are valid and refer to the preceding * content (of length ctx->dictSize), which is available * contiguously preceding in memory the content currently * being compressed. * - usingExtDict : Like withPrefix64k, but the preceding content is somewhere * else in memory, starting at ctx->dictionary with length * ctx->dictSize. * - usingDictCtx : Like usingExtDict, but everything concerning the preceding * content is in a separate context, pointed to by * ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table * entries in the current context that refer to positions * preceding the beginning of the current compression are * ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx * ->dictSize describe the location and size of the preceding * content, and matches are found by looking in the ctx * ->dictCtx->hashTable. */ typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive; typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive; /*-************************************ * Local Utils **************************************/ int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; } const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; } int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); } int LZ4_sizeofState() { return LZ4_STREAMSIZE; } /*-************************************ * Internal Definitions used in Tests **************************************/ #if defined (__cplusplus) extern "C" { #endif int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize); int LZ4_decompress_safe_forceExtDict(const char* in, char* out, int inSize, int outSize, const void* dict, size_t dictSize); #if defined (__cplusplus) } #endif /*-****************************** * Compression functions ********************************/ static U32 LZ4_hash4(U32 sequence, tableType_t const tableType) { if (tableType == byU16) return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1))); else return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG)); } static U32 LZ4_hash5(U64 sequence, tableType_t const tableType) { static const U64 prime5bytes = 889523592379ULL; static const U64 prime8bytes = 11400714785074694791ULL; const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG; if (LZ4_isLittleEndian()) return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog)); else return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog)); } LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType) { if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType); return LZ4_hash4(LZ4_read32(p), tableType); } static void LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableType_t const tableType) { switch (tableType) { default: /* fallthrough */ case clearedTable: /* fallthrough */ case byPtr: { /* illegal! */ assert(0); return; } case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; } case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; } } } static void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t const tableType, const BYTE* srcBase) { switch (tableType) { case clearedTable: { /* illegal! */ assert(0); return; } case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; } case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; } case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; } } } LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase) { U32 const h = LZ4_hashPosition(p, tableType); LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase); } /* LZ4_getIndexOnHash() : * Index of match position registered in hash table. * hash position must be calculated by using base+index, or dictBase+index. * Assumption 1 : only valid if tableType == byU32 or byU16. * Assumption 2 : h is presumed valid (within limits of hash table) */ static U32 LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_t tableType) { LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2); if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; assert(h < (1U << (LZ4_MEMORY_USAGE-2))); return hashTable[h]; } if (tableType == byU16) { const U16* const hashTable = (const U16*) tableBase; assert(h < (1U << (LZ4_MEMORY_USAGE-1))); return hashTable[h]; } assert(0); return 0; /* forbidden case */ } static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase) { if (tableType == byPtr) { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; } if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; return hashTable[h] + srcBase; } { const U16* const hashTable = (const U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */ } LZ4_FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p, const void* tableBase, tableType_t tableType, const BYTE* srcBase) { U32 const h = LZ4_hashPosition(p, tableType); return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase); } LZ4_FORCE_INLINE void LZ4_prepareTable( LZ4_stream_t_internal* const cctx, const int inputSize, const tableType_t tableType) { /* If the table hasn't been used, it's guaranteed to be zeroed out, and is * therefore safe to use no matter what mode we're in. Otherwise, we figure * out if it's safe to leave as is or whether it needs to be reset. */ if (cctx->tableType != clearedTable) { if (cctx->tableType != tableType || (tableType == byU16 && cctx->currentOffset + inputSize >= 0xFFFFU) || (tableType == byU32 && cctx->currentOffset > 1 GB) || tableType == byPtr || inputSize >= 4 KB) { DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", cctx); MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE); cctx->currentOffset = 0; cctx->tableType = clearedTable; } else { DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)"); } } /* Adding a gap, so all previous entries are > MAX_DISTANCE back, is faster * than compressing without a gap. However, compressing with * currentOffset == 0 is faster still, so we preserve that case. */ if (cctx->currentOffset != 0 && tableType == byU32) { DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset"); cctx->currentOffset += 64 KB; } /* Finally, clear history */ cctx->dictCtx = NULL; cctx->dictionary = NULL; cctx->dictSize = 0; } /** LZ4_compress_generic() : inlined, to ensure branches are decided at compilation time */ LZ4_FORCE_INLINE int LZ4_compress_generic( LZ4_stream_t_internal* const cctx, const char* const source, char* const dest, const int inputSize, int *inputConsumed, /* only written when outputLimited == fillOutput */ const int maxOutputSize, const limitedOutput_directive outputLimited, const tableType_t tableType, const dict_directive dictDirective, const dictIssue_directive dictIssue, const U32 acceleration) { const BYTE* ip = (const BYTE*) source; U32 const startIndex = cctx->currentOffset; const BYTE* base = (const BYTE*) source - startIndex; const BYTE* lowLimit; const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx; const BYTE* const dictionary = dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary; const U32 dictSize = dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize; const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0; /* make indexes in dictCtx comparable with index in current context */ int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx); U32 const prefixIdxLimit = startIndex - dictSize; /* used when dictDirective == dictSmall */ const BYTE* const dictEnd = dictionary + dictSize; const BYTE* anchor = (const BYTE*) source; const BYTE* const iend = ip + inputSize; const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1; const BYTE* const matchlimit = iend - LASTLITERALS; /* the dictCtx currentOffset is indexed on the start of the dictionary, * while a dictionary in the current context precedes the currentOffset */ const BYTE* dictBase = (dictDirective == usingDictCtx) ? dictionary + dictSize - dictCtx->currentOffset : dictionary + dictSize - startIndex; BYTE* op = (BYTE*) dest; BYTE* const olimit = op + maxOutputSize; U32 offset = 0; U32 forwardH; DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, tableType=%u", inputSize, tableType); /* Init conditions */ if (outputLimited == fillOutput && maxOutputSize < 1) return 0; /* Impossible to store anything */ if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */ if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ if (tableType==byPtr) assert(dictDirective==noDict); /* only supported use case with byPtr */ assert(acceleration >= 1); lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0); /* Update context state */ if (dictDirective == usingDictCtx) { /* Subsequent linked blocks can't use the dictionary. */ /* Instead, they use the block we just compressed. */ cctx->dictCtx = NULL; cctx->dictSize = (U32)inputSize; } else { cctx->dictSize += (U32)inputSize; } cctx->currentOffset += (U32)inputSize; cctx->tableType = (U16)tableType; if (inputSize<LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */ /* First Byte */ LZ4_putPosition(ip, cctx->hashTable, tableType, base); ip++; forwardH = LZ4_hashPosition(ip, tableType); /* Main Loop */ for ( ; ; ) { const BYTE* match; BYTE* token; /* Find a match */ if (tableType == byPtr) { const BYTE* forwardIp = ip; unsigned step = 1; unsigned searchMatchNb = acceleration << LZ4_skipTrigger; do { U32 const h = forwardH; ip = forwardIp; forwardIp += step; step = (searchMatchNb++ >> LZ4_skipTrigger); if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; assert(ip < mflimitPlusOne); match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base); forwardH = LZ4_hashPosition(forwardIp, tableType); LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base); } while ( (match+MAX_DISTANCE < ip) || (LZ4_read32(match) != LZ4_read32(ip)) ); } else { /* byU32, byU16 */ const BYTE* forwardIp = ip; unsigned step = 1; unsigned searchMatchNb = acceleration << LZ4_skipTrigger; do { U32 const h = forwardH; U32 const current = (U32)(forwardIp - base); U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); assert(matchIndex <= current); assert(forwardIp - base < (ptrdiff_t)(2 GB - 1)); ip = forwardIp; forwardIp += step; step = (searchMatchNb++ >> LZ4_skipTrigger); if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; assert(ip < mflimitPlusOne); if (dictDirective == usingDictCtx) { if (matchIndex < startIndex) { /* there was no match, try the dictionary */ assert(tableType == byU32); matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32); match = dictBase + matchIndex; matchIndex += dictDelta; /* make dictCtx index comparable with current context */ lowLimit = dictionary; } else { match = base + matchIndex; lowLimit = (const BYTE*)source; } } else if (dictDirective==usingExtDict) { if (matchIndex < startIndex) { DEBUGLOG(7, "extDict candidate: matchIndex=%5u < startIndex=%5u", matchIndex, startIndex); assert(startIndex - matchIndex >= MINMATCH); match = dictBase + matchIndex; lowLimit = dictionary; } else { match = base + matchIndex; lowLimit = (const BYTE*)source; } } else { /* single continuous memory segment */ match = base + matchIndex; } forwardH = LZ4_hashPosition(forwardIp, tableType); LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) continue; /* match outside of valid area */ assert(matchIndex < current); if ((tableType != byU16) && (matchIndex+MAX_DISTANCE < current)) continue; /* too far */ if (tableType == byU16) assert((current - matchIndex) <= MAX_DISTANCE); /* too_far presumed impossible with byU16 */ if (LZ4_read32(match) == LZ4_read32(ip)) { if (maybe_extMem) offset = current - matchIndex; break; /* match found */ } } while(1); } /* Catch up */ while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; } /* Encode Literals */ { unsigned const litLength = (unsigned)(ip - anchor); token = op++; if ((outputLimited == limitedOutput) && /* Check output buffer overflow */ (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit))) return 0; if ((outputLimited == fillOutput) && (unlikely(op + (litLength+240)/255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))) { op--; goto _last_literals; } if (litLength >= RUN_MASK) { int len = (int)litLength-RUN_MASK; *token = (RUN_MASK<<ML_BITS); for(; len >= 255 ; len-=255) *op++ = 255; *op++ = (BYTE)len; } else *token = (BYTE)(litLength<<ML_BITS); /* Copy Literals */ LZ4_wildCopy(op, anchor, op+litLength); op+=litLength; DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i", (int)(anchor-(const BYTE*)source), litLength, (int)(ip-(const BYTE*)source)); } _next_match: /* at this stage, the following variables must be correctly set : * - ip : at start of LZ operation * - match : at start of previous pattern occurence; can be within current prefix, or within extDict * - offset : if maybe_ext_memSegment==1 (constant) * - lowLimit : must be == dictionary to mean "match is within extDict"; must be == source otherwise * - token and *token : position to write 4-bits for match length; higher 4-bits for literal length supposed already written */ if ((outputLimited == fillOutput) && (op + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit)) { /* the match was too close to the end, rewind and go to last literals */ op = token; goto _last_literals; } /* Encode Offset */ if (maybe_extMem) { /* static test */ DEBUGLOG(6, " with offset=%u (ext if > %i)", offset, (int)(ip - (const BYTE*)source)); assert(offset <= MAX_DISTANCE && offset > 0); LZ4_writeLE16(op, (U16)offset); op+=2; } else { DEBUGLOG(6, " with offset=%u (same segment)", (U32)(ip - match)); assert(ip-match <= MAX_DISTANCE); LZ4_writeLE16(op, (U16)(ip - match)); op+=2; } /* Encode MatchLength */ { unsigned matchCode; if ( (dictDirective==usingExtDict || dictDirective==usingDictCtx) && (lowLimit==dictionary) /* match within extDict */ ) { const BYTE* limit = ip + (dictEnd-match); assert(dictEnd > match); if (limit > matchlimit) limit = matchlimit; matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit); ip += MINMATCH + matchCode; if (ip==limit) { unsigned const more = LZ4_count(limit, (const BYTE*)source, matchlimit); matchCode += more; ip += more; } DEBUGLOG(6, " with matchLength=%u starting in extDict", matchCode+MINMATCH); } else { matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit); ip += MINMATCH + matchCode; DEBUGLOG(6, " with matchLength=%u", matchCode+MINMATCH); } if ((outputLimited) && /* Check output buffer overflow */ (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) ) { if (outputLimited == limitedOutput) return 0; if (outputLimited == fillOutput) { /* Match description too long : reduce it */ U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 2 - 1 - LASTLITERALS) * 255; ip -= matchCode - newMatchCode; matchCode = newMatchCode; } } if (matchCode >= ML_MASK) { *token += ML_MASK; matchCode -= ML_MASK; LZ4_write32(op, 0xFFFFFFFF); while (matchCode >= 4*255) { op+=4; LZ4_write32(op, 0xFFFFFFFF); matchCode -= 4*255; } op += matchCode / 255; *op++ = (BYTE)(matchCode % 255); } else *token += (BYTE)(matchCode); } anchor = ip; /* Test end of chunk */ if (ip >= mflimitPlusOne) break; /* Fill table */ LZ4_putPosition(ip-2, cctx->hashTable, tableType, base); /* Test next position */ if (tableType == byPtr) { match = LZ4_getPosition(ip, cctx->hashTable, tableType, base); LZ4_putPosition(ip, cctx->hashTable, tableType, base); if ( (match+MAX_DISTANCE >= ip) && (LZ4_read32(match) == LZ4_read32(ip)) ) { token=op++; *token=0; goto _next_match; } } else { /* byU32, byU16 */ U32 const h = LZ4_hashPosition(ip, tableType); U32 const current = (U32)(ip-base); U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); assert(matchIndex < current); if (dictDirective == usingDictCtx) { if (matchIndex < startIndex) { /* there was no match, try the dictionary */ matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32); match = dictBase + matchIndex; lowLimit = dictionary; /* required for match length counter */ matchIndex += dictDelta; } else { match = base + matchIndex; lowLimit = (const BYTE*)source; /* required for match length counter */ } } else if (dictDirective==usingExtDict) { if (matchIndex < startIndex) { match = dictBase + matchIndex; lowLimit = dictionary; /* required for match length counter */ } else { match = base + matchIndex; lowLimit = (const BYTE*)source; /* required for match length counter */ } } else { /* single memory segment */ match = base + matchIndex; } LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); assert(matchIndex < current); if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1) && ((tableType==byU16) ? 1 : (matchIndex+MAX_DISTANCE >= current)) && (LZ4_read32(match) == LZ4_read32(ip)) ) { token=op++; *token=0; if (maybe_extMem) offset = current - matchIndex; DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i", (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source)); goto _next_match; } } /* Prepare next loop */ forwardH = LZ4_hashPosition(++ip, tableType); } _last_literals: /* Encode Last Literals */ { size_t lastRun = (size_t)(iend - anchor); if ( (outputLimited) && /* Check output buffer overflow */ (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) { if (outputLimited == fillOutput) { /* adapt lastRun to fill 'dst' */ lastRun = (olimit-op) - 1; lastRun -= (lastRun+240)/255; } if (outputLimited == limitedOutput) return 0; } if (lastRun >= RUN_MASK) { size_t accumulator = lastRun - RUN_MASK; *op++ = RUN_MASK << ML_BITS; for(; accumulator >= 255 ; accumulator-=255) *op++ = 255; *op++ = (BYTE) accumulator; } else { *op++ = (BYTE)(lastRun<<ML_BITS); } memcpy(op, anchor, lastRun); ip = anchor + lastRun; op += lastRun; } if (outputLimited == fillOutput) { *inputConsumed = (int) (((const char*)ip)-source); } DEBUGLOG(5, "LZ4_compress_generic: compressed %i bytes into %i bytes", inputSize, (int)(((char*)op) - dest)); return (int)(((char*)op) - dest); } int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) { LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse; if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; LZ4_resetStream((LZ4_stream_t*)state); if (maxOutputSize >= LZ4_compressBound(inputSize)) { if (inputSize < LZ4_64Klimit) { return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration); } else { const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > MAX_DISTANCE)) ? byPtr : byU32; return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); } } else { if (inputSize < LZ4_64Klimit) {; return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); } else { const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > MAX_DISTANCE)) ? byPtr : byU32; return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration); } } } /** * LZ4_compress_fast_extState_fastReset() : * A variant of LZ4_compress_fast_extState(). * * Using this variant avoids an expensive initialization step. It is only safe * to call if the state buffer is known to be correctly initialized already * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of * "correctly initialized"). */ int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration) { LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse; if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; if (dstCapacity >= LZ4_compressBound(srcSize)) { if (srcSize < LZ4_64Klimit) { const tableType_t tableType = byU16; LZ4_prepareTable(ctx, srcSize, tableType); if (ctx->currentOffset) { return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration); } else { return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); } } else { const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32; LZ4_prepareTable(ctx, srcSize, tableType); return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); } } else { if (srcSize < LZ4_64Klimit) { const tableType_t tableType = byU16; LZ4_prepareTable(ctx, srcSize, tableType); if (ctx->currentOffset) { return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration); } else { return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); } } else { const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32; LZ4_prepareTable(ctx, srcSize, tableType); return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); } } } int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) { int result; #if (LZ4_HEAPMODE) LZ4_stream_t* ctxPtr = ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ if (ctxPtr == NULL) return 0; #else LZ4_stream_t ctx; LZ4_stream_t* const ctxPtr = &ctx; #endif result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration); #if (LZ4_HEAPMODE) FREEMEM(ctxPtr); #endif return result; } int LZ4_compress_default(const char* source, char* dest, int inputSize, int maxOutputSize) { return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, 1); } /* hidden debug function */ /* strangely enough, gcc generates faster code when this function is uncommented, even if unused */ int LZ4_compress_fast_force(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) { LZ4_stream_t ctx; LZ4_resetStream(&ctx); if (inputSize < LZ4_64Klimit) return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); else return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, sizeof(void*)==8 ? byU32 : byPtr, noDict, noDictIssue, acceleration); } /* Note!: This function leaves the stream in an unclean/broken state! * It is not safe to subsequently use the same state with a _fastReset() or * _continue() call without resetting it. */ static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize) { LZ4_resetStream(state); if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) { /* compression success is guaranteed */ return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1); } else { if (*srcSizePtr < LZ4_64Klimit) { return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1); } else { tableType_t const tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32; return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, tableType, noDict, noDictIssue, 1); } } } int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize) { #if (LZ4_HEAPMODE) LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ if (ctx == NULL) return 0; #else LZ4_stream_t ctxBody; LZ4_stream_t* ctx = &ctxBody; #endif int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize); #if (LZ4_HEAPMODE) FREEMEM(ctx); #endif return result; } /*-****************************** * Streaming functions ********************************/ LZ4_stream_t* LZ4_createStream(void) { LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */ DEBUGLOG(4, "LZ4_createStream %p", lz4s); if (lz4s == NULL) return NULL; LZ4_resetStream(lz4s); return lz4s; } void LZ4_resetStream (LZ4_stream_t* LZ4_stream) { DEBUGLOG(5, "LZ4_resetStream (ctx:%p)", LZ4_stream); MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t)); } void LZ4_resetStream_fast(LZ4_stream_t* ctx) { LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32); } int LZ4_freeStream (LZ4_stream_t* LZ4_stream) { if (!LZ4_stream) return 0; /* support free on NULL */ DEBUGLOG(5, "LZ4_freeStream %p", LZ4_stream); FREEMEM(LZ4_stream); return (0); } #define HASH_UNIT sizeof(reg_t) int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize) { LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse; const tableType_t tableType = byU32; const BYTE* p = (const BYTE*)dictionary; const BYTE* const dictEnd = p + dictSize; const BYTE* base; DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict); /* It's necessary to reset the context, * and not just continue it with prepareTable() * to avoid any risk of generating overflowing matchIndex * when compressing using this dictionary */ LZ4_resetStream(LZ4_dict); /* We always increment the offset by 64 KB, since, if the dict is longer, * we truncate it to the last 64k, and if it's shorter, we still want to * advance by a whole window length so we can provide the guarantee that * there are only valid offsets in the window, which allows an optimization * in LZ4_compress_fast_continue() where it uses noDictIssue even when the * dictionary isn't a full 64k. */ if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB; base = dictEnd - 64 KB - dict->currentOffset; dict->dictionary = p; dict->dictSize = (U32)(dictEnd - p); dict->currentOffset += 64 KB; dict->tableType = tableType; if (dictSize < (int)HASH_UNIT) { return 0; } while (p <= dictEnd-HASH_UNIT) { LZ4_putPosition(p, dict->hashTable, tableType, base); p+=3; } return dict->dictSize; } void LZ4_attach_dictionary(LZ4_stream_t *working_stream, const LZ4_stream_t *dictionary_stream) { if (dictionary_stream != NULL) { /* If the current offset is zero, we will never look in the * external dictionary context, since there is no value a table * entry can take that indicate a miss. In that case, we need * to bump the offset to something non-zero. */ if (working_stream->internal_donotuse.currentOffset == 0) { working_stream->internal_donotuse.currentOffset = 64 KB; } working_stream->internal_donotuse.dictCtx = &(dictionary_stream->internal_donotuse); } else { working_stream->internal_donotuse.dictCtx = NULL; } } static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, int nextSize) { if (LZ4_dict->currentOffset + nextSize > 0x80000000) { /* potential ptrdiff_t overflow (32-bits mode) */ /* rescale hash table */ U32 const delta = LZ4_dict->currentOffset - 64 KB; const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize; int i; DEBUGLOG(4, "LZ4_renormDictT"); for (i=0; i<LZ4_HASH_SIZE_U32; i++) { if (LZ4_dict->hashTable[i] < delta) LZ4_dict->hashTable[i]=0; else LZ4_dict->hashTable[i] -= delta; } LZ4_dict->currentOffset = 64 KB; if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB; LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize; } } int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) { const tableType_t tableType = byU32; LZ4_stream_t_internal* streamPtr = &LZ4_stream->internal_donotuse; const BYTE* dictEnd = streamPtr->dictionary + streamPtr->dictSize; DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i)", inputSize); if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */ LZ4_renormDictT(streamPtr, inputSize); /* avoid index overflow */ if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; /* invalidate tiny dictionaries */ if ( (streamPtr->dictSize-1 < 4) /* intentional underflow */ && (dictEnd != (const BYTE*)source) ) { DEBUGLOG(5, "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", streamPtr->dictSize, streamPtr->dictionary); streamPtr->dictSize = 0; streamPtr->dictionary = (const BYTE*)source; dictEnd = (const BYTE*)source; } /* Check overlapping input/dictionary space */ { const BYTE* sourceEnd = (const BYTE*) source + inputSize; if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd)) { streamPtr->dictSize = (U32)(dictEnd - sourceEnd); if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB; if (streamPtr->dictSize < 4) streamPtr->dictSize = 0; streamPtr->dictionary = dictEnd - streamPtr->dictSize; } } /* prefix mode : source data follows dictionary */ if (dictEnd == (const BYTE*)source) { if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration); else return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration); } /* external dictionary mode */ { int result; if (streamPtr->dictCtx) { /* We depend here on the fact that dictCtx'es (produced by * LZ4_loadDict) guarantee that their tables contain no references * to offsets between dictCtx->currentOffset - 64 KB and * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe * to use noDictIssue even when the dict isn't a full 64 KB. */ if (inputSize > 4 KB) { /* For compressing large blobs, it is faster to pay the setup * cost to copy the dictionary's tables into the active context, * so that the compression loop is only looking into one table. */ memcpy(streamPtr, streamPtr->dictCtx, sizeof(LZ4_stream_t)); result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); } else { result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration); } } else { if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration); } else { result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); } } streamPtr->dictionary = (const BYTE*)source; streamPtr->dictSize = (U32)inputSize; return result; } } /* Hidden debug function, to force-test external dictionary mode */ int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize) { LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse; int result; LZ4_renormDictT(streamPtr, srcSize); if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1); } else { result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1); } streamPtr->dictionary = (const BYTE*)source; streamPtr->dictSize = (U32)srcSize; return result; } /*! LZ4_saveDict() : * If previously compressed data block is not guaranteed to remain available at its memory location, * save it into a safer place (char* safeBuffer). * Note : you don't need to call LZ4_loadDict() afterwards, * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue(). * Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error. */ int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize) { LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse; const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize; if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */ if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize; memmove(safeBuffer, previousDictEnd - dictSize, dictSize); dict->dictionary = (const BYTE*)safeBuffer; dict->dictSize = (U32)dictSize; return dictSize; } /*-******************************* * Decompression functions ********************************/ typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive; #undef MIN #define MIN(a,b) ( (a) < (b) ? (a) : (b) ) /*! LZ4_decompress_generic() : * This generic decompression function covers all use cases. * It shall be instantiated several times, using different sets of directives. * Note that it is important for performance that this function really get inlined, * in order to remove useless branches during compilation optimization. */ LZ4_FORCE_INLINE int LZ4_decompress_generic( const char* const src, char* const dst, int srcSize, int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */ endCondition_directive endOnInput, /* endOnOutputSize, endOnInputSize */ earlyEnd_directive partialDecoding, /* full, partial */ dict_directive dict, /* noDict, withPrefix64k, usingExtDict */ const BYTE* const lowPrefix, /* always <= dst, == dst when no prefix */ const BYTE* const dictStart, /* only if dict==usingExtDict */ const size_t dictSize /* note : = 0 if noDict */ ) { const BYTE* ip = (const BYTE*) src; const BYTE* const iend = ip + srcSize; BYTE* op = (BYTE*) dst; BYTE* const oend = op + outputSize; BYTE* cpy; const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize; const unsigned inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4}; const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3}; const int safeDecode = (endOnInput==endOnInputSize); const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB))); /* Set up the "end" pointers for the shortcut. */ const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/; const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/; DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize); /* Special cases */ assert(lowPrefix <= op); assert(src != NULL); if ((endOnInput) && (unlikely(outputSize==0))) return ((srcSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */ if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0 ? 1 : -1); if ((endOnInput) && unlikely(srcSize==0)) return -1; /* Main Loop : decode sequences */ while (1) { const BYTE* match; size_t offset; unsigned const token = *ip++; size_t length = token >> ML_BITS; /* literal length */ assert(!endOnInput || ip <= iend); /* ip < iend before the increment */ /* A two-stage shortcut for the most common case: * 1) If the literal length is 0..14, and there is enough space, * enter the shortcut and copy 16 bytes on behalf of the literals * (in the fast mode, only 8 bytes can be safely copied this way). * 2) Further if the match length is 4..18, copy 18 bytes in a similar * manner; but we ensure that there's enough space in the output for * those 18 bytes earlier, upon entering the shortcut (in other words, * there is a combined check for both stages). */ if ( (endOnInput ? length != RUN_MASK : length <= 8) /* strictly "less than" on input, to re-enter the loop with at least one byte */ && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) { /* Copy the literals */ memcpy(op, ip, endOnInput ? 16 : 8); op += length; ip += length; /* The second stage: prepare for match copying, decode full info. * If it doesn't work out, the info won't be wasted. */ length = token & ML_MASK; /* match length */ offset = LZ4_readLE16(ip); ip += 2; match = op - offset; assert(match <= op); /* check overflow */ /* Do not deal with overlapping matches. */ if ( (length != ML_MASK) && (offset >= 8) && (dict==withPrefix64k || match >= lowPrefix) ) { /* Copy the match. */ memcpy(op + 0, match + 0, 8); memcpy(op + 8, match + 8, 8); memcpy(op +16, match +16, 2); op += length + MINMATCH; /* Both stages worked, load the next token. */ continue; } /* The second stage didn't work out, but the info is ready. * Propel it right to the point of match copying. */ goto _copy_match; } /* decode literal length */ if (length == RUN_MASK) { unsigned s; if (unlikely(endOnInput ? ip >= iend-RUN_MASK : 0)) goto _output_error; /* overflow detection */ do { s = *ip++; length += s; } while ( likely(endOnInput ? ip<iend-RUN_MASK : 1) & (s==255) ); if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) goto _output_error; /* overflow detection */ if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) goto _output_error; /* overflow detection */ } /* copy literals */ cpy = op+length; LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); if ( ((endOnInput) && ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) ) || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) ) { if (partialDecoding) { if (cpy > oend) { cpy = oend; length = oend-op; } /* Partial decoding : stop in the middle of literal segment */ if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */ } else { if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */ if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */ } memcpy(op, ip, length); ip += length; op += length; if (!partialDecoding || (cpy == oend)) { /* Necessarily EOF, due to parsing restrictions */ break; } } else { LZ4_wildCopy(op, ip, cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */ ip += length; op = cpy; } /* get offset */ offset = LZ4_readLE16(ip); ip+=2; match = op - offset; /* get matchlength */ length = token & ML_MASK; _copy_match: if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */ if (!partialDecoding) { assert(oend > op); assert(oend - op >= 4); LZ4_write32(op, 0); /* silence an msan warning when offset==0; costs <1%; */ } /* note : when partialDecoding, there is no guarantee that at least 4 bytes remain available in output buffer */ if (length == ML_MASK) { unsigned s; do { s = *ip++; if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error; length += s; } while (s==255); if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */ } length += MINMATCH; /* match starting within external dictionary */ if ((dict==usingExtDict) && (match < lowPrefix)) { if (unlikely(op+length > oend-LASTLITERALS)) { if (partialDecoding) length = MIN(length, (size_t)(oend-op)); else goto _output_error; /* doesn't respect parsing restriction */ } if (length <= (size_t)(lowPrefix-match)) { /* match fits entirely within external dictionary : just copy */ memmove(op, dictEnd - (lowPrefix-match), length); op += length; } else { /* match stretches into both external dictionary and current block */ size_t const copySize = (size_t)(lowPrefix - match); size_t const restSize = length - copySize; memcpy(op, dictEnd - copySize, copySize); op += copySize; if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */ BYTE* const endOfMatch = op + restSize; const BYTE* copyFrom = lowPrefix; while (op < endOfMatch) *op++ = *copyFrom++; } else { memcpy(op, lowPrefix, restSize); op += restSize; } } continue; } /* copy match within block */ cpy = op + length; /* partialDecoding : may not respect endBlock parsing restrictions */ assert(op<=oend); if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { size_t const mlen = MIN(length, (size_t)(oend-op)); const BYTE* const matchEnd = match + mlen; BYTE* const copyEnd = op + mlen; if (matchEnd > op) { /* overlap copy */ while (op < copyEnd) *op++ = *match++; } else { memcpy(op, match, mlen); } op = copyEnd; if (op==oend) break; continue; } if (unlikely(offset<8)) { op[0] = match[0]; op[1] = match[1]; op[2] = match[2]; op[3] = match[3]; match += inc32table[offset]; memcpy(op+4, match, 4); match -= dec64table[offset]; } else { memcpy(op, match, 8); match += 8; } op += 8; if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1); if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ if (op < oCopyLimit) { LZ4_wildCopy(op, match, oCopyLimit); match += oCopyLimit - op; op = oCopyLimit; } while (op < cpy) *op++ = *match++; } else { memcpy(op, match, 8); if (length > 16) LZ4_wildCopy(op+8, match+8, cpy); } op = cpy; /* wildcopy correction */ } /* end of decoding */ if (endOnInput) return (int) (((char*)op)-dst); /* Nb of output bytes decoded */ else return (int) (((const char*)ip)-src); /* Nb of input bytes read */ /* Overflow error detected */ _output_error: return (int) (-(((const char*)ip)-src))-1; } /*===== Instantiate the API decoding functions. =====*/ LZ4_FORCE_O2_GCC_PPC64LE int LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize) { return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, decode_full_block, noDict, (BYTE*)dest, NULL, 0); } LZ4_FORCE_O2_GCC_PPC64LE int LZ4_decompress_safe_partial(const char* src, char* dst, int compressedSize, int targetOutputSize, int dstCapacity) { dstCapacity = MIN(targetOutputSize, dstCapacity); return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity, endOnInputSize, partial_decode, noDict, (BYTE*)dst, NULL, 0); } LZ4_FORCE_O2_GCC_PPC64LE int LZ4_decompress_fast(const char* source, char* dest, int originalSize) { return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, decode_full_block, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 0); } /*===== Instantiate a few more decoding cases, used more than once. =====*/ LZ4_FORCE_O2_GCC_PPC64LE /* Exported, an obsolete API function. */ int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize) { return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, decode_full_block, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 0); } /* Another obsolete API function, paired with the previous one. */ int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize) { /* LZ4_decompress_fast doesn't validate match offsets, * and thus serves well with any prefixed dictionary. */ return LZ4_decompress_fast(source, dest, originalSize); } LZ4_FORCE_O2_GCC_PPC64LE static int LZ4_decompress_safe_withSmallPrefix(const char* source, char* dest, int compressedSize, int maxOutputSize, size_t prefixSize) { return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, decode_full_block, noDict, (BYTE*)dest-prefixSize, NULL, 0); } LZ4_FORCE_O2_GCC_PPC64LE int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const void* dictStart, size_t dictSize) { return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, decode_full_block, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize); } LZ4_FORCE_O2_GCC_PPC64LE static int LZ4_decompress_fast_extDict(const char* source, char* dest, int originalSize, const void* dictStart, size_t dictSize) { return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, decode_full_block, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize); } /* The "double dictionary" mode, for use with e.g. ring buffers: the first part * of the dictionary is passed as prefix, and the second via dictStart + dictSize. * These routines are used only once, in LZ4_decompress_*_continue(). */ LZ4_FORCE_INLINE int LZ4_decompress_safe_doubleDict(const char* source, char* dest, int compressedSize, int maxOutputSize, size_t prefixSize, const void* dictStart, size_t dictSize) { return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, decode_full_block, usingExtDict, (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize); } LZ4_FORCE_INLINE int LZ4_decompress_fast_doubleDict(const char* source, char* dest, int originalSize, size_t prefixSize, const void* dictStart, size_t dictSize) { return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, decode_full_block, usingExtDict, (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize); } /*===== streaming decompression functions =====*/ LZ4_streamDecode_t* LZ4_createStreamDecode(void) { LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t)); return lz4s; } int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream) { if (!LZ4_stream) return 0; /* support free on NULL */ FREEMEM(LZ4_stream); return 0; } /*! LZ4_setStreamDecode() : * Use this function to instruct where to find the dictionary. * This function is not necessary if previous data is still available where it was decoded. * Loading a size of 0 is allowed (same effect as no dictionary). * @return : 1 if OK, 0 if error */ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize) { LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; lz4sd->prefixSize = (size_t) dictSize; lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize; lz4sd->externalDict = NULL; lz4sd->extDictSize = 0; return 1; } /*! LZ4_decoderRingBufferSize() : * when setting a ring buffer for streaming decompression (optional scenario), * provides the minimum size of this ring buffer * to be compatible with any source respecting maxBlockSize condition. * Note : in a ring buffer scenario, * blocks are presumed decompressed next to each other. * When not enough space remains for next block (remainingSize < maxBlockSize), * decoding resumes from beginning of ring buffer. * @return : minimum ring buffer size, * or 0 if there is an error (invalid maxBlockSize). */ int LZ4_decoderRingBufferSize(int maxBlockSize) { if (maxBlockSize < 0) return 0; if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0; if (maxBlockSize < 16) maxBlockSize = 16; return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize); } /* *_continue() : These decoding functions allow decompression of multiple blocks in "streaming" mode. Previously decoded blocks must still be available at the memory position where they were decoded. If it's not possible, save the relevant part of decoded data into a safe buffer, and indicate where it stands using LZ4_setStreamDecode() */ LZ4_FORCE_O2_GCC_PPC64LE int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize) { LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; int result; if (lz4sd->prefixSize == 0) { /* The first call, no dictionary yet. */ assert(lz4sd->extDictSize == 0); result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize); if (result <= 0) return result; lz4sd->prefixSize = result; lz4sd->prefixEnd = (BYTE*)dest + result; } else if (lz4sd->prefixEnd == (BYTE*)dest) { /* They're rolling the current segment. */ if (lz4sd->prefixSize >= 64 KB - 1) result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize); else if (lz4sd->extDictSize == 0) result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, lz4sd->prefixSize); else result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize, lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; lz4sd->prefixSize += result; lz4sd->prefixEnd += result; } else { /* The buffer wraps around, or they're switching to another buffer. */ lz4sd->extDictSize = lz4sd->prefixSize; lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; lz4sd->prefixSize = result; lz4sd->prefixEnd = (BYTE*)dest + result; } return result; } LZ4_FORCE_O2_GCC_PPC64LE int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize) { LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; int result; if (lz4sd->prefixSize == 0) { assert(lz4sd->extDictSize == 0); result = LZ4_decompress_fast(source, dest, originalSize); if (result <= 0) return result; lz4sd->prefixSize = originalSize; lz4sd->prefixEnd = (BYTE*)dest + originalSize; } else if (lz4sd->prefixEnd == (BYTE*)dest) { if (lz4sd->prefixSize >= 64 KB - 1 || lz4sd->extDictSize == 0) result = LZ4_decompress_fast(source, dest, originalSize); else result = LZ4_decompress_fast_doubleDict(source, dest, originalSize, lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; lz4sd->prefixSize += originalSize; lz4sd->prefixEnd += originalSize; } else { lz4sd->extDictSize = lz4sd->prefixSize; lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; result = LZ4_decompress_fast_extDict(source, dest, originalSize, lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; lz4sd->prefixSize = originalSize; lz4sd->prefixEnd = (BYTE*)dest + originalSize; } return result; } /* Advanced decoding functions : *_usingDict() : These decoding functions work the same as "_continue" ones, the dictionary must be explicitly provided within parameters */ int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize) { if (dictSize==0) return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize); if (dictStart+dictSize == dest) { if (dictSize >= 64 KB - 1) return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize); return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, dictSize); } return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, dictSize); } int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize) { if (dictSize==0 || dictStart+dictSize == dest) return LZ4_decompress_fast(source, dest, originalSize); return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, dictSize); } /*=************************************************* * Obsolete Functions ***************************************************/ /* obsolete compression functions */ int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) { return LZ4_compress_default(source, dest, inputSize, maxOutputSize); } int LZ4_compress(const char* source, char* dest, int inputSize) { return LZ4_compress_default(source, dest, inputSize, LZ4_compressBound(inputSize)); } int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); } int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); } int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity) { return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1); } int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) { return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); } /* These decompression functions are deprecated and should no longer be used. They are only provided here for compatibility with older user programs. - LZ4_uncompress is totally equivalent to LZ4_decompress_fast - LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe */ int LZ4_uncompress (const char* source, char* dest, int outputSize) { return LZ4_decompress_fast(source, dest, outputSize); } int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) { return LZ4_decompress_safe(source, dest, isize, maxOutputSize); } /* Obsolete Streaming functions */ int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; } int LZ4_resetStreamState(void* state, char* inputBuffer) { (void)inputBuffer; LZ4_resetStream((LZ4_stream_t*)state); return 0; } void* LZ4_create (char* inputBuffer) { (void)inputBuffer; return LZ4_createStream(); } char* LZ4_slideInputBuffer (void* state) { /* avoid const char * -> char * conversion warning */ return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary; } #endif /* LZ4_COMMONDEFS_ONLY */
82,353
1,953
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/COPYING
.ident "\n LZ4cli - LZ4 Command Line Interface (GPL v2) Copyright (C) Yann Collet 2011-2016 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. You can contact the author at : - LZ4 source repository : https://github.com/lz4/lz4 - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c"
926
22
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/lz4io.c
/* clang-format off */ /* LZ4io.c - LZ4 File/Stream Interface Copyright (C) Yann Collet 2011-2017 GPL v2 License This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. You can contact the author at : - LZ4 source repository : https://github.com/lz4/lz4 - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c */ /* Note : this is stand-alone program. It is not part of LZ4 compression library, it is a user code of the LZ4 library. - The license of LZ4 library is BSD. - The license of xxHash library is BSD. - The license of this source file is GPLv2. */ /*-************************************ * Compiler options **************************************/ #ifdef _MSC_VER /* Visual Studio */ # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ #endif #if defined(__MINGW32__) && !defined(_POSIX_SOURCE) # define _POSIX_SOURCE 1 /* disable %llu warnings with MinGW on Windows */ #endif /***************************** * Includes *****************************/ #include "third_party/lz4cli/platform.h" #include "third_party/lz4cli/util.h" #include "libc/stdio/stdio.h" #include "third_party/lz4cli/lz4io.h" #include "third_party/lz4cli/lz4.h" /* still required for legacy format */ #include "third_party/lz4cli/lz4hc.h" /* still required for legacy format */ #define LZ4F_STATIC_LINKING_ONLY #include "libc/runtime/runtime.h" #include "third_party/lz4cli/lz4frame.h" /***************************** * Constants *****************************/ #define KB *(1 <<10) #define MB *(1 <<20) #define GB *(1U<<30) #define _1BIT 0x01 #define _2BITS 0x03 #define _3BITS 0x07 #define _4BITS 0x0F #define _8BITS 0xFF #define MAGICNUMBER_SIZE 4 #define LZ4IO_MAGICNUMBER 0x184D2204 #define LZ4IO_SKIPPABLE0 0x184D2A50 #define LZ4IO_SKIPPABLEMASK 0xFFFFFFF0 #define LEGACY_MAGICNUMBER 0x184C2102 /* #define CACHELINE 64 */ #define LEGACY_BLOCKSIZE (8 MB) #define MIN_STREAM_BUFSIZE (192 KB) #define LZ4IO_BLOCKSIZEID_DEFAULT 7 #define LZ4_MAX_DICT_SIZE (64 KB) /************************************** * Macros **************************************/ #define DISPLAY(...) fprintf(stderr, __VA_ARGS__) #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } static int g_displayLevel = 0; /* 0 : no display ; 1: errors ; 2 : + result + interaction + warnings ; 3 : + progression; 4 : + information */ #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \ if ( ((clock() - g_time) > refreshRate) \ || (g_displayLevel>=4) ) { \ g_time = clock(); \ DISPLAY(__VA_ARGS__); \ if (g_displayLevel>=4) fflush(stderr); \ } } static clock_t g_time = 0; static clock_t refreshRate = CLOCKS_PER_SEC * 6; /************************************** * Local Parameters **************************************/ static int g_overwrite = 1; static int g_testMode = 0; static int g_blockSizeId = LZ4IO_BLOCKSIZEID_DEFAULT; static int g_blockChecksum = 0; static int g_streamChecksum = 1; static int g_blockIndependence = 1; static int g_sparseFileSupport = 1; static int g_contentSizeFlag = 0; static int g_useDictionary = 0; static unsigned g_favorDecSpeed = 0; static const char* g_dictionaryFilename = NULL; /************************************** * Exceptions ***************************************/ #ifndef DEBUG # define DEBUG 0 #endif #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__); #define EXM_THROW(error, ...) \ { \ DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \ DISPLAYLEVEL(1, "Error %i : ", error); \ DISPLAYLEVEL(1, __VA_ARGS__); \ DISPLAYLEVEL(1, " \n"); \ exit(error); \ } /************************************** * Version modifiers **************************************/ #define EXTENDED_ARGUMENTS #define EXTENDED_HELP #define EXTENDED_FORMAT #define DEFAULT_DECOMPRESSOR LZ4IO_decompressLZ4F /* ************************************************** */ /* ****************** Parameters ******************** */ /* ************************************************** */ int LZ4IO_setDictionaryFilename(const char* dictionaryFilename) { g_dictionaryFilename = dictionaryFilename; g_useDictionary = dictionaryFilename != NULL; return g_useDictionary; } /* Default setting : overwrite = 1; return : overwrite mode (0/1) */ int LZ4IO_setOverwrite(int yes) { g_overwrite = (yes!=0); return g_overwrite; } /* Default setting : testMode = 0; return : testMode (0/1) */ int LZ4IO_setTestMode(int yes) { g_testMode = (yes!=0); return g_testMode; } /* blockSizeID : valid values : 4-5-6-7 */ size_t LZ4IO_setBlockSizeID(unsigned bsid) { static const size_t blockSizeTable[] = { 64 KB, 256 KB, 1 MB, 4 MB }; static const unsigned minBlockSizeID = 4; static const unsigned maxBlockSizeID = 7; if ((bsid < minBlockSizeID) || (bsid > maxBlockSizeID)) return 0; g_blockSizeId = bsid; return blockSizeTable[g_blockSizeId-minBlockSizeID]; } int LZ4IO_setBlockMode(LZ4IO_blockMode_t blockMode) { g_blockIndependence = (blockMode == LZ4IO_blockIndependent); return g_blockIndependence; } /* Default setting : no block checksum */ int LZ4IO_setBlockChecksumMode(int enable) { g_blockChecksum = (enable != 0); return g_blockChecksum; } /* Default setting : checksum enabled */ int LZ4IO_setStreamChecksumMode(int enable) { g_streamChecksum = (enable != 0); return g_streamChecksum; } /* Default setting : 0 (no notification) */ int LZ4IO_setNotificationLevel(int level) { g_displayLevel = level; return g_displayLevel; } /* Default setting : 0 (disabled) */ int LZ4IO_setSparseFile(int enable) { g_sparseFileSupport = (enable!=0); return g_sparseFileSupport; } /* Default setting : 0 (disabled) */ int LZ4IO_setContentSize(int enable) { g_contentSizeFlag = (enable!=0); return g_contentSizeFlag; } /* Default setting : 0 (disabled) */ void LZ4IO_favorDecSpeed(int favor) { g_favorDecSpeed = (favor!=0); } static U32 g_removeSrcFile = 0; void LZ4IO_setRemoveSrcFile(unsigned flag) { g_removeSrcFile = (flag>0); } /* ************************************************************************ ** ** ********************** LZ4 File / Pipe compression ********************* ** ** ************************************************************************ */ static int LZ4IO_GetBlockSize_FromBlockId (int id) { return (1 << (8 + (2 * id))); } static int LZ4IO_isSkippableMagicNumber(unsigned int magic) { return (magic & LZ4IO_SKIPPABLEMASK) == LZ4IO_SKIPPABLE0; } /** LZ4IO_openSrcFile() : * condition : `srcFileName` must be non-NULL. * @result : FILE* to `dstFileName`, or NULL if it fails */ static FILE* LZ4IO_openSrcFile(const char* srcFileName) { FILE* f; if (!strcmp (srcFileName, stdinmark)) { DISPLAYLEVEL(4,"Using stdin for input\n"); f = stdin; SET_BINARY_MODE(stdin); } else { f = fopen(srcFileName, "rb"); if ( f==NULL ) DISPLAYLEVEL(1, "%s: %s \n", srcFileName, strerror(errno)); } return f; } /** FIO_openDstFile() : * condition : `dstFileName` must be non-NULL. * @result : FILE* to `dstFileName`, or NULL if it fails */ static FILE* LZ4IO_openDstFile(const char* dstFileName) { FILE* f; if (!strcmp (dstFileName, stdoutmark)) { DISPLAYLEVEL(4,"Using stdout for output\n"); f = stdout; SET_BINARY_MODE(stdout); if (g_sparseFileSupport==1) { g_sparseFileSupport = 0; DISPLAYLEVEL(4, "Sparse File Support is automatically disabled on stdout ; try --sparse \n"); } } else { if (!g_overwrite && strcmp (dstFileName, nulmark)) { /* Check if destination file already exists */ f = fopen( dstFileName, "rb" ); if (f != NULL) { /* dest exists, prompt for overwrite authorization */ fclose(f); if (g_displayLevel <= 1) { /* No interaction possible */ DISPLAY("%s already exists; not overwritten \n", dstFileName); return NULL; } DISPLAY("%s already exists; do you wish to overwrite (y/N) ? ", dstFileName); { int ch = getchar(); if ((ch!='Y') && (ch!='y')) { DISPLAY(" not overwritten \n"); return NULL; } while ((ch!=EOF) && (ch!='\n')) ch = getchar(); /* flush rest of input line */ } } } f = fopen( dstFileName, "wb" ); if (f==NULL) DISPLAYLEVEL(1, "%s: %s\n", dstFileName, strerror(errno)); } /* sparse file */ if (f && g_sparseFileSupport) { SET_SPARSE_FILE_MODE(f); } return f; } /*************************************** * Legacy Compression ***************************************/ /* unoptimized version; solves endianess & alignment issues */ static void LZ4IO_writeLE32 (void* p, unsigned value32) { unsigned char* const dstPtr = (unsigned char*)p; dstPtr[0] = (unsigned char)value32; dstPtr[1] = (unsigned char)(value32 >> 8); dstPtr[2] = (unsigned char)(value32 >> 16); dstPtr[3] = (unsigned char)(value32 >> 24); } static int LZ4IO_LZ4_compress(const char* src, char* dst, int srcSize, int dstSize, int cLevel) { (void)cLevel; return LZ4_compress_fast(src, dst, srcSize, dstSize, 1); } /* LZ4IO_compressFilename_Legacy : * This function is intentionally "hidden" (not published in .h) * It generates compressed streams using the old 'legacy' format */ int LZ4IO_compressFilename_Legacy(const char* input_filename, const char* output_filename, int compressionlevel) { int (*compressionFunction)(const char* src, char* dst, int srcSize, int dstSize, int cLevel); unsigned long long filesize = 0; unsigned long long compressedfilesize = MAGICNUMBER_SIZE; char* in_buff; char* out_buff; const int outBuffSize = LZ4_compressBound(LEGACY_BLOCKSIZE); FILE* finput; FILE* foutput; clock_t clockEnd; /* Init */ clock_t const clockStart = clock(); compressionFunction = (compressionlevel < 3) ? LZ4IO_LZ4_compress : LZ4_compress_HC; finput = LZ4IO_openSrcFile(input_filename); if (finput == NULL) EXM_THROW(20, "%s : open file error ", input_filename); foutput = LZ4IO_openDstFile(output_filename); if (foutput == NULL) { fclose(finput); EXM_THROW(20, "%s : open file error ", input_filename); } /* Allocate Memory */ in_buff = (char*)malloc(LEGACY_BLOCKSIZE); out_buff = (char*)malloc(outBuffSize); if (!in_buff || !out_buff) EXM_THROW(21, "Allocation error : not enough memory"); /* Write Archive Header */ LZ4IO_writeLE32(out_buff, LEGACY_MAGICNUMBER); { size_t const sizeCheck = fwrite(out_buff, 1, MAGICNUMBER_SIZE, foutput); if (sizeCheck != MAGICNUMBER_SIZE) EXM_THROW(22, "Write error : cannot write header"); } /* Main Loop */ while (1) { unsigned int outSize; /* Read Block */ size_t const inSize = (int) fread(in_buff, (size_t)1, (size_t)LEGACY_BLOCKSIZE, finput); if (inSize == 0) break; if (inSize > LEGACY_BLOCKSIZE) EXM_THROW(23, "Read error : wrong fread() size report "); /* should be impossible */ filesize += inSize; /* Compress Block */ outSize = compressionFunction(in_buff, out_buff+4, (int)inSize, outBuffSize, compressionlevel); compressedfilesize += outSize+4; DISPLAYUPDATE(2, "\rRead : %i MB ==> %.2f%% ", (int)(filesize>>20), (double)compressedfilesize/filesize*100); /* Write Block */ LZ4IO_writeLE32(out_buff, outSize); { size_t const sizeCheck = fwrite(out_buff, 1, outSize+4, foutput); if (sizeCheck!=(size_t)(outSize+4)) EXM_THROW(24, "Write error : cannot write compressed block"); } } if (ferror(finput)) EXM_THROW(25, "Error while reading %s ", input_filename); /* Status */ clockEnd = clock(); if (clockEnd==clockStart) clockEnd+=1; /* avoid division by zero (speed) */ filesize += !filesize; /* avoid division by zero (ratio) */ DISPLAYLEVEL(2, "\r%79s\r", ""); /* blank line */ DISPLAYLEVEL(2,"Compressed %llu bytes into %llu bytes ==> %.2f%%\n", filesize, compressedfilesize, (double)compressedfilesize / filesize * 100); { double const seconds = (double)(clockEnd - clockStart) / CLOCKS_PER_SEC; DISPLAYLEVEL(4,"Done in %.2f s ==> %.2f MB/s\n", seconds, (double)filesize / seconds / 1024 / 1024); } /* Close & Free */ free(in_buff); free(out_buff); fclose(finput); fclose(foutput); return 0; } /********************************************* * Compression using Frame format *********************************************/ typedef struct { void* srcBuffer; size_t srcBufferSize; void* dstBuffer; size_t dstBufferSize; LZ4F_compressionContext_t ctx; LZ4F_CDict* cdict; } cRess_t; static void* LZ4IO_createDict(const char* dictFilename, size_t *dictSize) { size_t readSize; size_t dictEnd = 0; size_t dictLen = 0; size_t dictStart; size_t circularBufSize = LZ4_MAX_DICT_SIZE; char* circularBuf; char* dictBuf; FILE* dictFile; if (!dictFilename) EXM_THROW(25, "Dictionary error : no filename provided"); circularBuf = (char *) malloc(circularBufSize); if (!circularBuf) EXM_THROW(25, "Allocation error : not enough memory"); dictFile = LZ4IO_openSrcFile(dictFilename); if (!dictFile) EXM_THROW(25, "Dictionary error : could not open dictionary file"); /* opportunistically seek to the part of the file we care about. If this */ /* fails it's not a problem since we'll just read everything anyways. */ if (strcmp(dictFilename, stdinmark)) { (void)UTIL_fseek(dictFile, -LZ4_MAX_DICT_SIZE, SEEK_END); } do { readSize = fread(circularBuf + dictEnd, 1, circularBufSize - dictEnd, dictFile); dictEnd = (dictEnd + readSize) % circularBufSize; dictLen += readSize; } while (readSize>0); if (dictLen > LZ4_MAX_DICT_SIZE) { dictLen = LZ4_MAX_DICT_SIZE; } *dictSize = dictLen; dictStart = (circularBufSize + dictEnd - dictLen) % circularBufSize; if (dictStart == 0) { /* We're in the simple case where the dict starts at the beginning of our circular buffer. */ dictBuf = circularBuf; circularBuf = NULL; } else { /* Otherwise, we will alloc a new buffer and copy our dict into that. */ dictBuf = (char *) malloc(dictLen ? dictLen : 1); if (!dictBuf) EXM_THROW(25, "Allocation error : not enough memory"); memcpy(dictBuf, circularBuf + dictStart, circularBufSize - dictStart); memcpy(dictBuf + circularBufSize - dictStart, circularBuf, dictLen - (circularBufSize - dictStart)); } fclose(dictFile); free(circularBuf); return dictBuf; } static LZ4F_CDict* LZ4IO_createCDict(void) { size_t dictionarySize; void* dictionaryBuffer; LZ4F_CDict* cdict; if (!g_useDictionary) { return NULL; } dictionaryBuffer = LZ4IO_createDict(g_dictionaryFilename, &dictionarySize); if (!dictionaryBuffer) EXM_THROW(25, "Dictionary error : could not create dictionary"); cdict = LZ4F_createCDict(dictionaryBuffer, dictionarySize); free(dictionaryBuffer); return cdict; } static cRess_t LZ4IO_createCResources(void) { const size_t blockSize = (size_t)LZ4IO_GetBlockSize_FromBlockId (g_blockSizeId); cRess_t ress; LZ4F_errorCode_t const errorCode = LZ4F_createCompressionContext(&(ress.ctx), LZ4F_VERSION); if (LZ4F_isError(errorCode)) EXM_THROW(30, "Allocation error : can't create LZ4F context : %s", LZ4F_getErrorName(errorCode)); /* Allocate Memory */ ress.srcBuffer = malloc(blockSize); ress.srcBufferSize = blockSize; ress.dstBufferSize = LZ4F_compressFrameBound(blockSize, NULL); /* cover worst case */ ress.dstBuffer = malloc(ress.dstBufferSize); if (!ress.srcBuffer || !ress.dstBuffer) EXM_THROW(31, "Allocation error : not enough memory"); ress.cdict = LZ4IO_createCDict(); return ress; } static void LZ4IO_freeCResources(cRess_t ress) { free(ress.srcBuffer); free(ress.dstBuffer); LZ4F_freeCDict(ress.cdict); ress.cdict = NULL; { LZ4F_errorCode_t const errorCode = LZ4F_freeCompressionContext(ress.ctx); if (LZ4F_isError(errorCode)) EXM_THROW(38, "Error : can't free LZ4F context resource : %s", LZ4F_getErrorName(errorCode)); } } /* * LZ4IO_compressFilename_extRess() * result : 0 : compression completed correctly * 1 : missing or pb opening srcFileName */ static int LZ4IO_compressFilename_extRess(cRess_t ress, const char* srcFileName, const char* dstFileName, int compressionLevel) { unsigned long long filesize = 0; unsigned long long compressedfilesize = 0; FILE* srcFile; FILE* dstFile; void* const srcBuffer = ress.srcBuffer; void* const dstBuffer = ress.dstBuffer; const size_t dstBufferSize = ress.dstBufferSize; const size_t blockSize = (size_t)LZ4IO_GetBlockSize_FromBlockId (g_blockSizeId); size_t readSize; LZ4F_compressionContext_t ctx = ress.ctx; /* just a pointer */ LZ4F_preferences_t prefs; /* Init */ srcFile = LZ4IO_openSrcFile(srcFileName); if (srcFile == NULL) return 1; dstFile = LZ4IO_openDstFile(dstFileName); if (dstFile == NULL) { fclose(srcFile); return 1; } memset(&prefs, 0, sizeof(prefs)); /* Set compression parameters */ prefs.autoFlush = 1; prefs.compressionLevel = compressionLevel; prefs.frameInfo.blockMode = (LZ4F_blockMode_t)g_blockIndependence; prefs.frameInfo.blockSizeID = (LZ4F_blockSizeID_t)g_blockSizeId; prefs.frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)g_blockChecksum; prefs.frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)g_streamChecksum; prefs.favorDecSpeed = g_favorDecSpeed; if (g_contentSizeFlag) { U64 const fileSize = UTIL_getFileSize(srcFileName); prefs.frameInfo.contentSize = fileSize; /* == 0 if input == stdin */ if (fileSize==0) DISPLAYLEVEL(3, "Warning : cannot determine input content size \n"); } /* read first block */ readSize = fread(srcBuffer, (size_t)1, blockSize, srcFile); if (ferror(srcFile)) EXM_THROW(30, "Error reading %s ", srcFileName); filesize += readSize; /* single-block file */ if (readSize < blockSize) { /* Compress in single pass */ size_t cSize = LZ4F_compressFrame_usingCDict(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, ress.cdict, &prefs); if (LZ4F_isError(cSize)) EXM_THROW(31, "Compression failed : %s", LZ4F_getErrorName(cSize)); compressedfilesize = cSize; DISPLAYUPDATE(2, "\rRead : %u MB ==> %.2f%% ", (unsigned)(filesize>>20), (double)compressedfilesize/(filesize+!filesize)*100); /* avoid division by zero */ /* Write Block */ { size_t const sizeCheck = fwrite(dstBuffer, 1, cSize, dstFile); if (sizeCheck!=cSize) EXM_THROW(32, "Write error : cannot write compressed block"); } } else /* multiple-blocks file */ { /* Write Archive Header */ size_t headerSize = LZ4F_compressBegin_usingCDict(ctx, dstBuffer, dstBufferSize, ress.cdict, &prefs); if (LZ4F_isError(headerSize)) EXM_THROW(33, "File header generation failed : %s", LZ4F_getErrorName(headerSize)); { size_t const sizeCheck = fwrite(dstBuffer, 1, headerSize, dstFile); if (sizeCheck!=headerSize) EXM_THROW(34, "Write error : cannot write header"); } compressedfilesize += headerSize; /* Main Loop */ while (readSize>0) { size_t outSize; /* Compress Block */ outSize = LZ4F_compressUpdate(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, NULL); if (LZ4F_isError(outSize)) EXM_THROW(35, "Compression failed : %s", LZ4F_getErrorName(outSize)); compressedfilesize += outSize; DISPLAYUPDATE(2, "\rRead : %u MB ==> %.2f%% ", (unsigned)(filesize>>20), (double)compressedfilesize/filesize*100); /* Write Block */ { size_t const sizeCheck = fwrite(dstBuffer, 1, outSize, dstFile); if (sizeCheck!=outSize) EXM_THROW(36, "Write error : cannot write compressed block"); } /* Read next block */ readSize = fread(srcBuffer, (size_t)1, (size_t)blockSize, srcFile); filesize += readSize; } if (ferror(srcFile)) EXM_THROW(37, "Error reading %s ", srcFileName); /* End of Stream mark */ headerSize = LZ4F_compressEnd(ctx, dstBuffer, dstBufferSize, NULL); if (LZ4F_isError(headerSize)) EXM_THROW(38, "End of file generation failed : %s", LZ4F_getErrorName(headerSize)); { size_t const sizeCheck = fwrite(dstBuffer, 1, headerSize, dstFile); if (sizeCheck!=headerSize) EXM_THROW(39, "Write error : cannot write end of stream"); } compressedfilesize += headerSize; } /* Release files */ fclose (srcFile); fclose (dstFile); /* Copy owner, file permissions and modification time */ { struct stat statbuf; if (strcmp (srcFileName, stdinmark) && strcmp (dstFileName, stdoutmark) && strcmp (dstFileName, nulmark) && UTIL_getFileStat(srcFileName, &statbuf)) { UTIL_setFileStat(dstFileName, &statbuf); } } if (g_removeSrcFile) { /* remove source file : --rm */ if (remove(srcFileName)) EXM_THROW(40, "Remove error : %s: %s", srcFileName, strerror(errno)); } /* Final Status */ DISPLAYLEVEL(2, "\r%79s\r", ""); DISPLAYLEVEL(2, "Compressed %llu bytes into %llu bytes ==> %.2f%%\n", filesize, compressedfilesize, (double)compressedfilesize / (filesize + !filesize /* avoid division by zero */ ) * 100); return 0; } int LZ4IO_compressFilename(const char* srcFileName, const char* dstFileName, int compressionLevel) { UTIL_time_t const timeStart = UTIL_getTime(); clock_t const cpuStart = clock(); cRess_t const ress = LZ4IO_createCResources(); int const result = LZ4IO_compressFilename_extRess(ress, srcFileName, dstFileName, compressionLevel); /* Free resources */ LZ4IO_freeCResources(ress); /* Final Status */ { clock_t const cpuEnd = clock(); double const cpuLoad_s = (double)(cpuEnd - cpuStart) / CLOCKS_PER_SEC; U64 const timeLength_ns = UTIL_clockSpanNano(timeStart); double const timeLength_s = (double)timeLength_ns / 1000000000; DISPLAYLEVEL(4, "Completed in %.2f sec (cpu load : %.0f%%)\n", timeLength_s, (cpuLoad_s / timeLength_s) * 100); } return result; } #define FNSPACE 30 int LZ4IO_compressMultipleFilenames(const char** inFileNamesTable, int ifntSize, const char* suffix, int compressionLevel) { int i; int missed_files = 0; char* dstFileName = (char*)malloc(FNSPACE); size_t ofnSize = FNSPACE; const size_t suffixSize = strlen(suffix); cRess_t ress; if (dstFileName == NULL) return ifntSize; /* not enough memory */ ress = LZ4IO_createCResources(); /* loop on each file */ for (i=0; i<ifntSize; i++) { size_t const ifnSize = strlen(inFileNamesTable[i]); if (ofnSize <= ifnSize+suffixSize+1) { free(dstFileName); ofnSize = ifnSize + 20; dstFileName = (char*)malloc(ofnSize); if (dstFileName==NULL) { LZ4IO_freeCResources(ress); return ifntSize; } } strcpy(dstFileName, inFileNamesTable[i]); strcat(dstFileName, suffix); missed_files += LZ4IO_compressFilename_extRess(ress, inFileNamesTable[i], dstFileName, compressionLevel); } /* Close & Free */ LZ4IO_freeCResources(ress); free(dstFileName); return missed_files; } /* ********************************************************************* */ /* ********************** LZ4 file-stream Decompression **************** */ /* ********************************************************************* */ static unsigned LZ4IO_readLE32 (const void* s) { const unsigned char* const srcPtr = (const unsigned char*)s; unsigned value32 = srcPtr[0]; value32 += (srcPtr[1]<<8); value32 += (srcPtr[2]<<16); value32 += ((unsigned)srcPtr[3])<<24; return value32; } static unsigned LZ4IO_fwriteSparse(FILE* file, const void* buffer, size_t bufferSize, unsigned storedSkips) { const size_t sizeT = sizeof(size_t); const size_t maskT = sizeT -1 ; const size_t* const bufferT = (const size_t*)buffer; /* Buffer is supposed malloc'ed, hence aligned on size_t */ const size_t* ptrT = bufferT; size_t bufferSizeT = bufferSize / sizeT; const size_t* const bufferTEnd = bufferT + bufferSizeT; const size_t segmentSizeT = (32 KB) / sizeT; if (!g_sparseFileSupport) { /* normal write */ size_t const sizeCheck = fwrite(buffer, 1, bufferSize, file); if (sizeCheck != bufferSize) EXM_THROW(70, "Write error : cannot write decoded block"); return 0; } /* avoid int overflow */ if (storedSkips > 1 GB) { int const seekResult = UTIL_fseek(file, 1 GB, SEEK_CUR); if (seekResult != 0) EXM_THROW(71, "1 GB skip error (sparse file support)"); storedSkips -= 1 GB; } while (ptrT < bufferTEnd) { size_t seg0SizeT = segmentSizeT; size_t nb0T; /* count leading zeros */ if (seg0SizeT > bufferSizeT) seg0SizeT = bufferSizeT; bufferSizeT -= seg0SizeT; for (nb0T=0; (nb0T < seg0SizeT) && (ptrT[nb0T] == 0); nb0T++) ; storedSkips += (unsigned)(nb0T * sizeT); if (nb0T != seg0SizeT) { /* not all 0s */ errno = 0; { int const seekResult = UTIL_fseek(file, storedSkips, SEEK_CUR); if (seekResult) EXM_THROW(72, "Sparse skip error(%d): %s ; try --no-sparse", (int)errno, strerror(errno)); } storedSkips = 0; seg0SizeT -= nb0T; ptrT += nb0T; { size_t const sizeCheck = fwrite(ptrT, sizeT, seg0SizeT, file); if (sizeCheck != seg0SizeT) EXM_THROW(73, "Write error : cannot write decoded block"); } } ptrT += seg0SizeT; } if (bufferSize & maskT) { /* size not multiple of sizeT : implies end of block */ const char* const restStart = (const char*)bufferTEnd; const char* restPtr = restStart; size_t const restSize = bufferSize & maskT; const char* const restEnd = restStart + restSize; for (; (restPtr < restEnd) && (*restPtr == 0); restPtr++) ; storedSkips += (unsigned) (restPtr - restStart); if (restPtr != restEnd) { int const seekResult = UTIL_fseek(file, storedSkips, SEEK_CUR); if (seekResult) EXM_THROW(74, "Sparse skip error ; try --no-sparse"); storedSkips = 0; { size_t const sizeCheck = fwrite(restPtr, 1, restEnd - restPtr, file); if (sizeCheck != (size_t)(restEnd - restPtr)) EXM_THROW(75, "Write error : cannot write decoded end of block"); } } } return storedSkips; } static void LZ4IO_fwriteSparseEnd(FILE* file, unsigned storedSkips) { if (storedSkips>0) { /* implies g_sparseFileSupport>0 */ int const seekResult = UTIL_fseek(file, storedSkips-1, SEEK_CUR); if (seekResult != 0) EXM_THROW(69, "Final skip error (sparse file)\n"); { const char lastZeroByte[1] = { 0 }; size_t const sizeCheck = fwrite(lastZeroByte, 1, 1, file); if (sizeCheck != 1) EXM_THROW(69, "Write error : cannot write last zero\n"); } } } static unsigned g_magicRead = 0; /* out-parameter of LZ4IO_decodeLegacyStream() */ static unsigned long long LZ4IO_decodeLegacyStream(FILE* finput, FILE* foutput) { unsigned long long streamSize = 0; unsigned storedSkips = 0; /* Allocate Memory */ char* const in_buff = (char*)malloc(LZ4_compressBound(LEGACY_BLOCKSIZE)); char* const out_buff = (char*)malloc(LEGACY_BLOCKSIZE); if (!in_buff || !out_buff) EXM_THROW(51, "Allocation error : not enough memory"); /* Main Loop */ while (1) { unsigned int blockSize; /* Block Size */ { size_t const sizeCheck = fread(in_buff, 1, 4, finput); if (sizeCheck == 0) break; /* Nothing to read : file read is completed */ if (sizeCheck != 4) EXM_THROW(52, "Read error : cannot access block size "); } blockSize = LZ4IO_readLE32(in_buff); /* Convert to Little Endian */ if (blockSize > LZ4_COMPRESSBOUND(LEGACY_BLOCKSIZE)) { /* Cannot read next block : maybe new stream ? */ g_magicRead = blockSize; break; } /* Read Block */ { size_t const sizeCheck = fread(in_buff, 1, blockSize, finput); if (sizeCheck!=blockSize) EXM_THROW(52, "Read error : cannot access compressed block !"); } /* Decode Block */ { int const decodeSize = LZ4_decompress_safe(in_buff, out_buff, blockSize, LEGACY_BLOCKSIZE); if (decodeSize < 0) EXM_THROW(53, "Decoding Failed ! Corrupted input detected !"); streamSize += decodeSize; /* Write Block */ storedSkips = LZ4IO_fwriteSparse(foutput, out_buff, decodeSize, storedSkips); /* success or die */ } } if (ferror(finput)) EXM_THROW(54, "Read error : ferror"); LZ4IO_fwriteSparseEnd(foutput, storedSkips); /* Free */ free(in_buff); free(out_buff); return streamSize; } typedef struct { void* srcBuffer; size_t srcBufferSize; void* dstBuffer; size_t dstBufferSize; FILE* dstFile; LZ4F_decompressionContext_t dCtx; void* dictBuffer; size_t dictBufferSize; } dRess_t; static void LZ4IO_loadDDict(dRess_t* ress) { if (!g_useDictionary) { ress->dictBuffer = NULL; ress->dictBufferSize = 0; return; } ress->dictBuffer = LZ4IO_createDict(g_dictionaryFilename, &ress->dictBufferSize); if (!ress->dictBuffer) EXM_THROW(25, "Dictionary error : could not create dictionary"); } static const size_t LZ4IO_dBufferSize = 64 KB; static dRess_t LZ4IO_createDResources(void) { dRess_t ress; /* init */ LZ4F_errorCode_t const errorCode = LZ4F_createDecompressionContext(&ress.dCtx, LZ4F_VERSION); if (LZ4F_isError(errorCode)) EXM_THROW(60, "Can't create LZ4F context : %s", LZ4F_getErrorName(errorCode)); /* Allocate Memory */ ress.srcBufferSize = LZ4IO_dBufferSize; ress.srcBuffer = malloc(ress.srcBufferSize); ress.dstBufferSize = LZ4IO_dBufferSize; ress.dstBuffer = malloc(ress.dstBufferSize); if (!ress.srcBuffer || !ress.dstBuffer) EXM_THROW(61, "Allocation error : not enough memory"); LZ4IO_loadDDict(&ress); ress.dstFile = NULL; return ress; } static void LZ4IO_freeDResources(dRess_t ress) { LZ4F_errorCode_t errorCode = LZ4F_freeDecompressionContext(ress.dCtx); if (LZ4F_isError(errorCode)) EXM_THROW(69, "Error : can't free LZ4F context resource : %s", LZ4F_getErrorName(errorCode)); free(ress.srcBuffer); free(ress.dstBuffer); free(ress.dictBuffer); } static unsigned long long LZ4IO_decompressLZ4F(dRess_t ress, FILE* srcFile, FILE* dstFile) { unsigned long long filesize = 0; LZ4F_errorCode_t nextToLoad; unsigned storedSkips = 0; /* Init feed with magic number (already consumed from FILE* sFile) */ { size_t inSize = MAGICNUMBER_SIZE; size_t outSize= 0; LZ4IO_writeLE32(ress.srcBuffer, LZ4IO_MAGICNUMBER); nextToLoad = LZ4F_decompress_usingDict(ress.dCtx, ress.dstBuffer, &outSize, ress.srcBuffer, &inSize, ress.dictBuffer, ress.dictBufferSize, NULL); if (LZ4F_isError(nextToLoad)) EXM_THROW(62, "Header error : %s", LZ4F_getErrorName(nextToLoad)); } /* Main Loop */ for (;nextToLoad;) { size_t readSize; size_t pos = 0; size_t decodedBytes = ress.dstBufferSize; /* Read input */ if (nextToLoad > ress.srcBufferSize) nextToLoad = ress.srcBufferSize; readSize = fread(ress.srcBuffer, 1, nextToLoad, srcFile); if (!readSize) break; /* reached end of file or stream */ while ((pos < readSize) || (decodedBytes == ress.dstBufferSize)) { /* still to read, or still to flush */ /* Decode Input (at least partially) */ size_t remaining = readSize - pos; decodedBytes = ress.dstBufferSize; nextToLoad = LZ4F_decompress_usingDict(ress.dCtx, ress.dstBuffer, &decodedBytes, (char*)(ress.srcBuffer)+pos, &remaining, ress.dictBuffer, ress.dictBufferSize, NULL); if (LZ4F_isError(nextToLoad)) EXM_THROW(66, "Decompression error : %s", LZ4F_getErrorName(nextToLoad)); pos += remaining; /* Write Block */ if (decodedBytes) { if (!g_testMode) storedSkips = LZ4IO_fwriteSparse(dstFile, ress.dstBuffer, decodedBytes, storedSkips); filesize += decodedBytes; DISPLAYUPDATE(2, "\rDecompressed : %u MB ", (unsigned)(filesize>>20)); } if (!nextToLoad) break; } } /* can be out because readSize == 0, which could be an fread() error */ if (ferror(srcFile)) EXM_THROW(67, "Read error"); if (!g_testMode) LZ4IO_fwriteSparseEnd(dstFile, storedSkips); if (nextToLoad!=0) EXM_THROW(68, "Unfinished stream"); return filesize; } #define PTSIZE (64 KB) #define PTSIZET (PTSIZE / sizeof(size_t)) static unsigned long long LZ4IO_passThrough(FILE* finput, FILE* foutput, unsigned char MNstore[MAGICNUMBER_SIZE]) { size_t buffer[PTSIZET]; size_t readBytes = 1; unsigned long long total = MAGICNUMBER_SIZE; unsigned storedSkips = 0; size_t const sizeCheck = fwrite(MNstore, 1, MAGICNUMBER_SIZE, foutput); if (sizeCheck != MAGICNUMBER_SIZE) EXM_THROW(50, "Pass-through write error"); while (readBytes) { readBytes = fread(buffer, 1, PTSIZE, finput); total += readBytes; storedSkips = LZ4IO_fwriteSparse(foutput, buffer, readBytes, storedSkips); } if (ferror(finput)) EXM_THROW(51, "Read Error"); LZ4IO_fwriteSparseEnd(foutput, storedSkips); return total; } /** Safely handle cases when (unsigned)offset > LONG_MAX */ static int fseek_u32(FILE *fp, unsigned offset, int where) { const unsigned stepMax = 1U << 30; int errorNb = 0; if (where != SEEK_CUR) return -1; /* Only allows SEEK_CUR */ while (offset > 0) { unsigned s = offset; if (s > stepMax) s = stepMax; errorNb = UTIL_fseek(fp, (long) s, SEEK_CUR); if (errorNb != 0) break; offset -= s; } return errorNb; } #define ENDOFSTREAM ((unsigned long long)-1) static unsigned long long selectDecoder(dRess_t ress, FILE* finput, FILE* foutput) { unsigned char MNstore[MAGICNUMBER_SIZE]; unsigned magicNumber; static unsigned nbFrames = 0; /* init */ nbFrames++; /* Check Archive Header */ if (g_magicRead) { /* magic number already read from finput (see legacy frame)*/ magicNumber = g_magicRead; g_magicRead = 0; } else { size_t const nbReadBytes = fread(MNstore, 1, MAGICNUMBER_SIZE, finput); if (nbReadBytes==0) { nbFrames = 0; return ENDOFSTREAM; } /* EOF */ if (nbReadBytes != MAGICNUMBER_SIZE) EXM_THROW(40, "Unrecognized header : Magic Number unreadable"); magicNumber = LZ4IO_readLE32(MNstore); /* Little Endian format */ } if (LZ4IO_isSkippableMagicNumber(magicNumber)) magicNumber = LZ4IO_SKIPPABLE0; /* fold skippable magic numbers */ switch(magicNumber) { case LZ4IO_MAGICNUMBER: return LZ4IO_decompressLZ4F(ress, finput, foutput); case LEGACY_MAGICNUMBER: DISPLAYLEVEL(4, "Detected : Legacy format \n"); return LZ4IO_decodeLegacyStream(finput, foutput); case LZ4IO_SKIPPABLE0: DISPLAYLEVEL(4, "Skipping detected skippable area \n"); { size_t const nbReadBytes = fread(MNstore, 1, 4, finput); if (nbReadBytes != 4) EXM_THROW(42, "Stream error : skippable size unreadable"); } { unsigned const size = LZ4IO_readLE32(MNstore); int const errorNb = fseek_u32(finput, size, SEEK_CUR); if (errorNb != 0) EXM_THROW(43, "Stream error : cannot skip skippable area"); } return 0; EXTENDED_FORMAT; /* macro extension for custom formats */ default: if (nbFrames == 1) { /* just started */ /* Wrong magic number at the beginning of 1st stream */ if (!g_testMode && g_overwrite) { nbFrames = 0; return LZ4IO_passThrough(finput, foutput, MNstore); } EXM_THROW(44,"Unrecognized header : file cannot be decoded"); } { long int const position = ftell(finput); /* only works for files < 2 GB */ DISPLAYLEVEL(2, "Stream followed by undecodable data "); if (position != -1L) DISPLAYLEVEL(2, "at position %i ", (int)position); DISPLAYLEVEL(2, "\n"); } return ENDOFSTREAM; } } static int LZ4IO_decompressSrcFile(dRess_t ress, const char* input_filename, const char* output_filename) { FILE* const foutput = ress.dstFile; unsigned long long filesize = 0; /* Init */ FILE* const finput = LZ4IO_openSrcFile(input_filename); if (finput==NULL) return 1; /* Loop over multiple streams */ for ( ; ; ) { /* endless loop, see break condition */ unsigned long long const decodedSize = selectDecoder(ress, finput, foutput); if (decodedSize == ENDOFSTREAM) break; filesize += decodedSize; } /* Close input */ fclose(finput); if (g_removeSrcFile) { /* --rm */ if (remove(input_filename)) EXM_THROW(45, "Remove error : %s: %s", input_filename, strerror(errno)); } /* Final Status */ DISPLAYLEVEL(2, "\r%79s\r", ""); DISPLAYLEVEL(2, "%-20.20s : decoded %llu bytes \n", input_filename, filesize); (void)output_filename; return 0; } static int LZ4IO_decompressDstFile(dRess_t ress, const char* input_filename, const char* output_filename) { struct stat statbuf; int stat_result = 0; FILE* const foutput = LZ4IO_openDstFile(output_filename); if (foutput==NULL) return 1; /* failure */ if ( strcmp(input_filename, stdinmark) && UTIL_getFileStat(input_filename, &statbuf)) stat_result = 1; ress.dstFile = foutput; LZ4IO_decompressSrcFile(ress, input_filename, output_filename); fclose(foutput); /* Copy owner, file permissions and modification time */ if ( stat_result != 0 && strcmp (output_filename, stdoutmark) && strcmp (output_filename, nulmark)) { UTIL_setFileStat(output_filename, &statbuf); /* should return value be read ? or is silent fail good enough ? */ } return 0; } int LZ4IO_decompressFilename(const char* input_filename, const char* output_filename) { dRess_t const ress = LZ4IO_createDResources(); clock_t const start = clock(); int const missingFiles = LZ4IO_decompressDstFile(ress, input_filename, output_filename); clock_t const end = clock(); double const seconds = (double)(end - start) / CLOCKS_PER_SEC; DISPLAYLEVEL(4, "Done in %.2f sec \n", seconds); LZ4IO_freeDResources(ress); return missingFiles; } int LZ4IO_decompressMultipleFilenames(const char** inFileNamesTable, int ifntSize, const char* suffix) { int i; int skippedFiles = 0; int missingFiles = 0; char* outFileName = (char*)malloc(FNSPACE); size_t ofnSize = FNSPACE; size_t const suffixSize = strlen(suffix); dRess_t ress = LZ4IO_createDResources(); if (outFileName==NULL) return ifntSize; /* not enough memory */ ress.dstFile = LZ4IO_openDstFile(stdoutmark); for (i=0; i<ifntSize; i++) { size_t const ifnSize = strlen(inFileNamesTable[i]); const char* const suffixPtr = inFileNamesTable[i] + ifnSize - suffixSize; if (!strcmp(suffix, stdoutmark)) { missingFiles += LZ4IO_decompressSrcFile(ress, inFileNamesTable[i], stdoutmark); continue; } if (ofnSize <= ifnSize-suffixSize+1) { free(outFileName); ofnSize = ifnSize + 20; outFileName = (char*)malloc(ofnSize); if (outFileName==NULL) return ifntSize; } if (ifnSize <= suffixSize || strcmp(suffixPtr, suffix) != 0) { DISPLAYLEVEL(1, "File extension doesn't match expected LZ4_EXTENSION (%4s); will not process file: %s\n", suffix, inFileNamesTable[i]); skippedFiles++; continue; } memcpy(outFileName, inFileNamesTable[i], ifnSize - suffixSize); outFileName[ifnSize-suffixSize] = '\0'; missingFiles += LZ4IO_decompressDstFile(ress, inFileNamesTable[i], outFileName); } LZ4IO_freeDResources(ress); free(outFileName); return missingFiles + skippedFiles; }
42,554
1,173
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/lz4frame.c
/* clang-format off */ /* LZ4 auto-framing library Copyright (C) 2011-2016, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) 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. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. You can contact the author at : - LZ4 homepage : http://www.lz4.org - LZ4 source repository : https://github.com/lz4/lz4 */ /* LZ4F is a stand-alone API to create LZ4-compressed Frames * in full conformance with specification v1.5.0 * All related operations, including memory management, are handled by the library. * */ /*-************************************ * Compiler Options **************************************/ #ifdef _MSC_VER /* Visual Studio */ # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ #endif /*-************************************ * Tuning parameters **************************************/ /* * LZ4F_HEAPMODE : * Select how default compression functions will allocate memory for their hash table, * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()). */ #ifndef LZ4F_HEAPMODE # define LZ4F_HEAPMODE 0 #endif /*-************************************ * Memory routines **************************************/ #include "libc/mem/mem.h" #define ALLOC(s) malloc(s) #define ALLOC_AND_ZERO(s) calloc(1,s) #define FREEMEM free #include "libc/assert.h" #include "libc/str/str.h" /* memset, memcpy, memmove */ #define MEM_INIT memset /*-************************************ * Includes **************************************/ #define LZ4F_STATIC_LINKING_ONLY #include "third_party/lz4cli/lz4frame.h" #define LZ4_STATIC_LINKING_ONLY #include "third_party/lz4cli/lz4.h" #define LZ4_HC_STATIC_LINKING_ONLY #include "third_party/lz4cli/lz4hc.h" #define XXH_STATIC_LINKING_ONLY #include "third_party/lz4cli/xxhash.h" #define LZ4F_STATIC_ASSERT(c) { enum { LZ4F_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */ #if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2) && !defined(DEBUGLOG) # include "libc/stdio/stdio.h" static int g_debuglog_enable = 1; # define DEBUGLOG(l, ...) { \ if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) { \ fprintf(stderr, __FILE__ ": "); \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, " \n"); \ } } #else # define DEBUGLOG(l, ...) {} /* disabled */ #endif /*-************************************ * Basic Types **************************************/ #if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) typedef uint8_t BYTE; typedef uint16_t U16; typedef uint32_t U32; typedef int32_t S32; typedef uint64_t U64; #else typedef unsigned char BYTE; typedef unsigned short U16; typedef unsigned int U32; typedef signed int S32; typedef unsigned long long U64; #endif /* unoptimized version; solves endianess & alignment issues */ static U32 LZ4F_readLE32 (const void* src) { const BYTE* const srcPtr = (const BYTE*)src; U32 value32 = srcPtr[0]; value32 += (srcPtr[1]<<8); value32 += (srcPtr[2]<<16); value32 += ((U32)srcPtr[3])<<24; return value32; } static void LZ4F_writeLE32 (void* dst, U32 value32) { BYTE* const dstPtr = (BYTE*)dst; dstPtr[0] = (BYTE)value32; dstPtr[1] = (BYTE)(value32 >> 8); dstPtr[2] = (BYTE)(value32 >> 16); dstPtr[3] = (BYTE)(value32 >> 24); } static U64 LZ4F_readLE64 (const void* src) { const BYTE* const srcPtr = (const BYTE*)src; U64 value64 = srcPtr[0]; value64 += ((U64)srcPtr[1]<<8); value64 += ((U64)srcPtr[2]<<16); value64 += ((U64)srcPtr[3]<<24); value64 += ((U64)srcPtr[4]<<32); value64 += ((U64)srcPtr[5]<<40); value64 += ((U64)srcPtr[6]<<48); value64 += ((U64)srcPtr[7]<<56); return value64; } static void LZ4F_writeLE64 (void* dst, U64 value64) { BYTE* const dstPtr = (BYTE*)dst; dstPtr[0] = (BYTE)value64; dstPtr[1] = (BYTE)(value64 >> 8); dstPtr[2] = (BYTE)(value64 >> 16); dstPtr[3] = (BYTE)(value64 >> 24); dstPtr[4] = (BYTE)(value64 >> 32); dstPtr[5] = (BYTE)(value64 >> 40); dstPtr[6] = (BYTE)(value64 >> 48); dstPtr[7] = (BYTE)(value64 >> 56); } /*-************************************ * Constants **************************************/ #define KB *(1<<10) #define MB *(1<<20) #define GB *(1<<30) #define _1BIT 0x01 #define _2BITS 0x03 #define _3BITS 0x07 #define _4BITS 0x0F #define _8BITS 0xFF #define LZ4F_MAGIC_SKIPPABLE_START 0x184D2A50U #define LZ4F_MAGICNUMBER 0x184D2204U #define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U #define LZ4F_BLOCKSIZEID_DEFAULT LZ4F_max64KB static const size_t minFHSize = 7; static const size_t maxFHSize = LZ4F_HEADER_SIZE_MAX; /* 19 */ static const size_t BHSize = 4; /*-************************************ * Structures and local types **************************************/ typedef struct LZ4F_cctx_s { LZ4F_preferences_t prefs; U32 version; U32 cStage; const LZ4F_CDict* cdict; size_t maxBlockSize; size_t maxBufferSize; BYTE* tmpBuff; BYTE* tmpIn; size_t tmpInSize; U64 totalInSize; XXH32_state_t xxh; void* lz4CtxPtr; U16 lz4CtxAlloc; /* sized for: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */ U16 lz4CtxState; /* in use as: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */ } LZ4F_cctx_t; /*-************************************ * Error management **************************************/ #define LZ4F_GENERATE_STRING(STRING) #STRING, static const char* LZ4F_errorStrings[] = { LZ4F_LIST_ERRORS(LZ4F_GENERATE_STRING) }; unsigned LZ4F_isError(LZ4F_errorCode_t code) { return (code > (LZ4F_errorCode_t)(-LZ4F_ERROR_maxCode)); } const char* LZ4F_getErrorName(LZ4F_errorCode_t code) { static const char* codeError = "Unspecified error code"; if (LZ4F_isError(code)) return LZ4F_errorStrings[-(int)(code)]; return codeError; } LZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult) { if (!LZ4F_isError(functionResult)) return LZ4F_OK_NoError; return (LZ4F_errorCodes)(-(ptrdiff_t)functionResult); } static LZ4F_errorCode_t err0r(LZ4F_errorCodes code) { /* A compilation error here means sizeof(ptrdiff_t) is not large enough */ LZ4F_STATIC_ASSERT(sizeof(ptrdiff_t) >= sizeof(size_t)); return (LZ4F_errorCode_t)-(ptrdiff_t)code; } unsigned LZ4F_getVersion(void) { return LZ4F_VERSION; } int LZ4F_compressionLevel_max(void) { return LZ4HC_CLEVEL_MAX; } /*-************************************ * Private functions **************************************/ #ifndef MIN #define MIN(a,b) ( (a) < (b) ? (a) : (b) ) #endif static size_t LZ4F_getBlockSize(unsigned blockSizeID) { static const size_t blockSizes[4] = { 64 KB, 256 KB, 1 MB, 4 MB }; if (blockSizeID == 0) blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT; blockSizeID -= 4; if (blockSizeID > 3) return err0r(LZ4F_ERROR_maxBlockSize_invalid); return blockSizes[blockSizeID]; } static BYTE LZ4F_headerChecksum (const void* header, size_t length) { U32 const xxh = XXH32(header, length, 0); return (BYTE)(xxh >> 8); } /*-************************************ * Simple-pass compression functions **************************************/ static LZ4F_blockSizeID_t LZ4F_optimalBSID(const LZ4F_blockSizeID_t requestedBSID, const size_t srcSize) { LZ4F_blockSizeID_t proposedBSID = LZ4F_max64KB; size_t maxBlockSize = 64 KB; while (requestedBSID > proposedBSID) { if (srcSize <= maxBlockSize) return proposedBSID; proposedBSID = (LZ4F_blockSizeID_t)((int)proposedBSID + 1); maxBlockSize <<= 2; } return requestedBSID; } /*! LZ4F_compressBound_internal() : * Provides dstCapacity given a srcSize to guarantee operation success in worst case situations. * prefsPtr is optional : if NULL is provided, preferences will be set to cover worst case scenario. * @return is always the same for a srcSize and prefsPtr, so it can be relied upon to size reusable buffers. * When srcSize==0, LZ4F_compressBound() provides an upper bound for LZ4F_flush() and LZ4F_compressEnd() operations. */ static size_t LZ4F_compressBound_internal(size_t srcSize, const LZ4F_preferences_t* preferencesPtr, size_t alreadyBuffered) { LZ4F_preferences_t prefsNull; MEM_INIT(&prefsNull, 0, sizeof(prefsNull)); prefsNull.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled; /* worst case */ { const LZ4F_preferences_t* const prefsPtr = (preferencesPtr==NULL) ? &prefsNull : preferencesPtr; U32 const flush = prefsPtr->autoFlush | (srcSize==0); LZ4F_blockSizeID_t const blockID = prefsPtr->frameInfo.blockSizeID; size_t const blockSize = LZ4F_getBlockSize(blockID); size_t const maxBuffered = blockSize - 1; size_t const bufferedSize = MIN(alreadyBuffered, maxBuffered); size_t const maxSrcSize = srcSize + bufferedSize; unsigned const nbFullBlocks = (unsigned)(maxSrcSize / blockSize); size_t const partialBlockSize = maxSrcSize & (blockSize-1); size_t const lastBlockSize = flush ? partialBlockSize : 0; unsigned const nbBlocks = nbFullBlocks + (lastBlockSize>0); size_t const blockHeaderSize = 4; size_t const blockCRCSize = 4 * prefsPtr->frameInfo.blockChecksumFlag; size_t const frameEnd = 4 + (prefsPtr->frameInfo.contentChecksumFlag*4); return ((blockHeaderSize + blockCRCSize) * nbBlocks) + (blockSize * nbFullBlocks) + lastBlockSize + frameEnd; } } size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr) { LZ4F_preferences_t prefs; size_t const headerSize = maxFHSize; /* max header size, including optional fields */ if (preferencesPtr!=NULL) prefs = *preferencesPtr; else MEM_INIT(&prefs, 0, sizeof(prefs)); prefs.autoFlush = 1; return headerSize + LZ4F_compressBound_internal(srcSize, &prefs, 0);; } /*! LZ4F_compressFrame_usingCDict() : * Compress srcBuffer using a dictionary, in a single step. * cdict can be NULL, in which case, no dictionary is used. * dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). * The LZ4F_preferences_t structure is optional : you may provide NULL as argument, * however, it's the only way to provide a dictID, so it's not recommended. * @return : number of bytes written into dstBuffer, * or an error code if it fails (can be tested using LZ4F_isError()) */ size_t LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx, void* dstBuffer, size_t dstCapacity, const void* srcBuffer, size_t srcSize, const LZ4F_CDict* cdict, const LZ4F_preferences_t* preferencesPtr) { LZ4F_preferences_t prefs; LZ4F_compressOptions_t options; BYTE* const dstStart = (BYTE*) dstBuffer; BYTE* dstPtr = dstStart; BYTE* const dstEnd = dstStart + dstCapacity; if (preferencesPtr!=NULL) prefs = *preferencesPtr; else MEM_INIT(&prefs, 0, sizeof(prefs)); if (prefs.frameInfo.contentSize != 0) prefs.frameInfo.contentSize = (U64)srcSize; /* auto-correct content size if selected (!=0) */ prefs.frameInfo.blockSizeID = LZ4F_optimalBSID(prefs.frameInfo.blockSizeID, srcSize); prefs.autoFlush = 1; if (srcSize <= LZ4F_getBlockSize(prefs.frameInfo.blockSizeID)) prefs.frameInfo.blockMode = LZ4F_blockIndependent; /* only one block => no need for inter-block link */ MEM_INIT(&options, 0, sizeof(options)); options.stableSrc = 1; if (dstCapacity < LZ4F_compressFrameBound(srcSize, &prefs)) /* condition to guarantee success */ return err0r(LZ4F_ERROR_dstMaxSize_tooSmall); { size_t const headerSize = LZ4F_compressBegin_usingCDict(cctx, dstBuffer, dstCapacity, cdict, &prefs); /* write header */ if (LZ4F_isError(headerSize)) return headerSize; dstPtr += headerSize; /* header size */ } { size_t const cSize = LZ4F_compressUpdate(cctx, dstPtr, dstEnd-dstPtr, srcBuffer, srcSize, &options); if (LZ4F_isError(cSize)) return cSize; dstPtr += cSize; } { size_t const tailSize = LZ4F_compressEnd(cctx, dstPtr, dstEnd-dstPtr, &options); /* flush last block, and generate suffix */ if (LZ4F_isError(tailSize)) return tailSize; dstPtr += tailSize; } return (dstPtr - dstStart); } /*! LZ4F_compressFrame() : * Compress an entire srcBuffer into a valid LZ4 frame, in a single step. * dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). * The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default. * @return : number of bytes written into dstBuffer. * or an error code if it fails (can be tested using LZ4F_isError()) */ size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity, const void* srcBuffer, size_t srcSize, const LZ4F_preferences_t* preferencesPtr) { size_t result; #if (LZ4F_HEAPMODE) LZ4F_cctx_t *cctxPtr; result = LZ4F_createCompressionContext(&cctxPtr, LZ4F_VERSION); if (LZ4F_isError(result)) return result; #else LZ4F_cctx_t cctx; LZ4_stream_t lz4ctx; LZ4F_cctx_t *cctxPtr = &cctx; DEBUGLOG(4, "LZ4F_compressFrame"); MEM_INIT(&cctx, 0, sizeof(cctx)); cctx.version = LZ4F_VERSION; cctx.maxBufferSize = 5 MB; /* mess with real buffer size to prevent dynamic allocation; works only because autoflush==1 & stableSrc==1 */ if (preferencesPtr == NULL || preferencesPtr->compressionLevel < LZ4HC_CLEVEL_MIN) { LZ4_resetStream(&lz4ctx); cctxPtr->lz4CtxPtr = &lz4ctx; cctxPtr->lz4CtxAlloc = 1; cctxPtr->lz4CtxState = 1; } #endif result = LZ4F_compressFrame_usingCDict(cctxPtr, dstBuffer, dstCapacity, srcBuffer, srcSize, NULL, preferencesPtr); #if (LZ4F_HEAPMODE) LZ4F_freeCompressionContext(cctxPtr); #else if (preferencesPtr != NULL && preferencesPtr->compressionLevel >= LZ4HC_CLEVEL_MIN) { FREEMEM(cctxPtr->lz4CtxPtr); } #endif return result; } /*-*************************************************** * Dictionary compression *****************************************************/ struct LZ4F_CDict_s { void* dictContent; LZ4_stream_t* fastCtx; LZ4_streamHC_t* HCCtx; }; /* typedef'd to LZ4F_CDict within lz4frame_static.h */ /*! LZ4F_createCDict() : * When compressing multiple messages / blocks with the same dictionary, it's recommended to load it just once. * LZ4F_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay. * LZ4F_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. * `dictBuffer` can be released after LZ4F_CDict creation, since its content is copied within CDict * @return : digested dictionary for compression, or NULL if failed */ LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize) { const char* dictStart = (const char*)dictBuffer; LZ4F_CDict* cdict = (LZ4F_CDict*) ALLOC(sizeof(*cdict)); DEBUGLOG(4, "LZ4F_createCDict"); if (!cdict) return NULL; if (dictSize > 64 KB) { dictStart += dictSize - 64 KB; dictSize = 64 KB; } cdict->dictContent = ALLOC(dictSize); cdict->fastCtx = LZ4_createStream(); cdict->HCCtx = LZ4_createStreamHC(); if (!cdict->dictContent || !cdict->fastCtx || !cdict->HCCtx) { LZ4F_freeCDict(cdict); return NULL; } memcpy(cdict->dictContent, dictStart, dictSize); LZ4_loadDict (cdict->fastCtx, (const char*)cdict->dictContent, (int)dictSize); LZ4_setCompressionLevel(cdict->HCCtx, LZ4HC_CLEVEL_DEFAULT); LZ4_loadDictHC(cdict->HCCtx, (const char*)cdict->dictContent, (int)dictSize); return cdict; } void LZ4F_freeCDict(LZ4F_CDict* cdict) { if (cdict==NULL) return; /* support free on NULL */ FREEMEM(cdict->dictContent); LZ4_freeStream(cdict->fastCtx); LZ4_freeStreamHC(cdict->HCCtx); FREEMEM(cdict); } /*-********************************* * Advanced compression functions ***********************************/ /*! LZ4F_createCompressionContext() : * The first thing to do is to create a compressionContext object, which will be used in all compression operations. * This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure. * The version provided MUST be LZ4F_VERSION. It is intended to track potential incompatible differences between different binaries. * The function will provide a pointer to an allocated LZ4F_compressionContext_t object. * If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation. * Object can release its memory using LZ4F_freeCompressionContext(); */ LZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_compressionContext_t* LZ4F_compressionContextPtr, unsigned version) { LZ4F_cctx_t* const cctxPtr = (LZ4F_cctx_t*)ALLOC_AND_ZERO(sizeof(LZ4F_cctx_t)); if (cctxPtr==NULL) return err0r(LZ4F_ERROR_allocation_failed); cctxPtr->version = version; cctxPtr->cStage = 0; /* Next stage : init stream */ *LZ4F_compressionContextPtr = (LZ4F_compressionContext_t)cctxPtr; return LZ4F_OK_NoError; } LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_compressionContext_t LZ4F_compressionContext) { LZ4F_cctx_t* const cctxPtr = (LZ4F_cctx_t*)LZ4F_compressionContext; if (cctxPtr != NULL) { /* support free on NULL */ FREEMEM(cctxPtr->lz4CtxPtr); /* works because LZ4_streamHC_t and LZ4_stream_t are simple POD types */ FREEMEM(cctxPtr->tmpBuff); FREEMEM(LZ4F_compressionContext); } return LZ4F_OK_NoError; } /** * This function prepares the internal LZ4(HC) stream for a new compression, * resetting the context and attaching the dictionary, if there is one. * * It needs to be called at the beginning of each independent compression * stream (i.e., at the beginning of a frame in blockLinked mode, or at the * beginning of each block in blockIndependent mode). */ static void LZ4F_initStream(void* ctx, const LZ4F_CDict* cdict, int level, LZ4F_blockMode_t blockMode) { if (level < LZ4HC_CLEVEL_MIN) { if (cdict != NULL || blockMode == LZ4F_blockLinked) { /* In these cases, we will call LZ4_compress_fast_continue(), * which needs an already reset context. Otherwise, we'll call a * one-shot API. The non-continued APIs internally perform their own * resets at the beginning of their calls, where they know what * tableType they need the context to be in. So in that case this * would be misguided / wasted work. */ LZ4_resetStream_fast((LZ4_stream_t*)ctx); } LZ4_attach_dictionary((LZ4_stream_t *)ctx, cdict ? cdict->fastCtx : NULL); } else { LZ4_resetStreamHC_fast((LZ4_streamHC_t*)ctx, level); LZ4_attach_HC_dictionary((LZ4_streamHC_t *)ctx, cdict ? cdict->HCCtx : NULL); } } /*! LZ4F_compressBegin_usingCDict() : * init streaming compression and writes frame header into dstBuffer. * dstBuffer must be >= LZ4F_HEADER_SIZE_MAX bytes. * @return : number of bytes written into dstBuffer for the header * or an error code (can be tested using LZ4F_isError()) */ size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctxPtr, void* dstBuffer, size_t dstCapacity, const LZ4F_CDict* cdict, const LZ4F_preferences_t* preferencesPtr) { LZ4F_preferences_t prefNull; BYTE* const dstStart = (BYTE*)dstBuffer; BYTE* dstPtr = dstStart; BYTE* headerStart; if (dstCapacity < maxFHSize) return err0r(LZ4F_ERROR_dstMaxSize_tooSmall); MEM_INIT(&prefNull, 0, sizeof(prefNull)); if (preferencesPtr == NULL) preferencesPtr = &prefNull; cctxPtr->prefs = *preferencesPtr; /* Ctx Management */ { U16 const ctxTypeID = (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ? 1 : 2; if (cctxPtr->lz4CtxAlloc < ctxTypeID) { FREEMEM(cctxPtr->lz4CtxPtr); if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) { cctxPtr->lz4CtxPtr = (void*)LZ4_createStream(); } else { cctxPtr->lz4CtxPtr = (void*)LZ4_createStreamHC(); } if (cctxPtr->lz4CtxPtr == NULL) return err0r(LZ4F_ERROR_allocation_failed); cctxPtr->lz4CtxAlloc = ctxTypeID; cctxPtr->lz4CtxState = ctxTypeID; } else if (cctxPtr->lz4CtxState != ctxTypeID) { /* otherwise, a sufficient buffer is allocated, but we need to * reset it to the correct context type */ if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) { LZ4_resetStream((LZ4_stream_t *) cctxPtr->lz4CtxPtr); } else { LZ4_resetStreamHC((LZ4_streamHC_t *) cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel); } cctxPtr->lz4CtxState = ctxTypeID; } } /* Buffer Management */ if (cctxPtr->prefs.frameInfo.blockSizeID == 0) cctxPtr->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT; cctxPtr->maxBlockSize = LZ4F_getBlockSize(cctxPtr->prefs.frameInfo.blockSizeID); { size_t const requiredBuffSize = preferencesPtr->autoFlush ? (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) * 64 KB : /* only needs windows size */ cctxPtr->maxBlockSize + ((cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) * 128 KB); if (cctxPtr->maxBufferSize < requiredBuffSize) { cctxPtr->maxBufferSize = 0; FREEMEM(cctxPtr->tmpBuff); cctxPtr->tmpBuff = (BYTE*)ALLOC_AND_ZERO(requiredBuffSize); if (cctxPtr->tmpBuff == NULL) return err0r(LZ4F_ERROR_allocation_failed); cctxPtr->maxBufferSize = requiredBuffSize; } } cctxPtr->tmpIn = cctxPtr->tmpBuff; cctxPtr->tmpInSize = 0; XXH32_reset(&(cctxPtr->xxh), 0); /* context init */ cctxPtr->cdict = cdict; if (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) { /* frame init only for blockLinked : blockIndependent will be init at each block */ LZ4F_initStream(cctxPtr->lz4CtxPtr, cdict, cctxPtr->prefs.compressionLevel, LZ4F_blockLinked); } if (preferencesPtr->compressionLevel >= LZ4HC_CLEVEL_MIN) { LZ4_favorDecompressionSpeed((LZ4_streamHC_t*)cctxPtr->lz4CtxPtr, (int)preferencesPtr->favorDecSpeed); } /* Magic Number */ LZ4F_writeLE32(dstPtr, LZ4F_MAGICNUMBER); dstPtr += 4; headerStart = dstPtr; /* FLG Byte */ *dstPtr++ = (BYTE)(((1 & _2BITS) << 6) /* Version('01') */ + ((cctxPtr->prefs.frameInfo.blockMode & _1BIT ) << 5) + ((cctxPtr->prefs.frameInfo.blockChecksumFlag & _1BIT ) << 4) + ((cctxPtr->prefs.frameInfo.contentSize > 0) << 3) + ((cctxPtr->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2) + (cctxPtr->prefs.frameInfo.dictID > 0) ); /* BD Byte */ *dstPtr++ = (BYTE)((cctxPtr->prefs.frameInfo.blockSizeID & _3BITS) << 4); /* Optional Frame content size field */ if (cctxPtr->prefs.frameInfo.contentSize) { LZ4F_writeLE64(dstPtr, cctxPtr->prefs.frameInfo.contentSize); dstPtr += 8; cctxPtr->totalInSize = 0; } /* Optional dictionary ID field */ if (cctxPtr->prefs.frameInfo.dictID) { LZ4F_writeLE32(dstPtr, cctxPtr->prefs.frameInfo.dictID); dstPtr += 4; } /* Header CRC Byte */ *dstPtr = LZ4F_headerChecksum(headerStart, dstPtr - headerStart); dstPtr++; cctxPtr->cStage = 1; /* header written, now request input data block */ return (dstPtr - dstStart); } /*! LZ4F_compressBegin() : * init streaming compression and writes frame header into dstBuffer. * dstBuffer must be >= LZ4F_HEADER_SIZE_MAX bytes. * preferencesPtr can be NULL, in which case default parameters are selected. * @return : number of bytes written into dstBuffer for the header * or an error code (can be tested using LZ4F_isError()) */ size_t LZ4F_compressBegin(LZ4F_cctx* cctxPtr, void* dstBuffer, size_t dstCapacity, const LZ4F_preferences_t* preferencesPtr) { return LZ4F_compressBegin_usingCDict(cctxPtr, dstBuffer, dstCapacity, NULL, preferencesPtr); } /* LZ4F_compressBound() : * @return minimum capacity of dstBuffer for a given srcSize to handle worst case scenario. * LZ4F_preferences_t structure is optional : if NULL, preferences will be set to cover worst case scenario. * This function cannot fail. */ size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr) { return LZ4F_compressBound_internal(srcSize, preferencesPtr, (size_t)-1); } typedef int (*compressFunc_t)(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level, const LZ4F_CDict* cdict); /*! LZ4F_makeBlock(): * compress a single block, add header and checksum * assumption : dst buffer capacity is >= srcSize */ static size_t LZ4F_makeBlock(void* dst, const void* src, size_t srcSize, compressFunc_t compress, void* lz4ctx, int level, const LZ4F_CDict* cdict, LZ4F_blockChecksum_t crcFlag) { BYTE* const cSizePtr = (BYTE*)dst; U32 cSize = (U32)compress(lz4ctx, (const char*)src, (char*)(cSizePtr+4), (int)(srcSize), (int)(srcSize-1), level, cdict); LZ4F_writeLE32(cSizePtr, cSize); if (cSize == 0) { /* compression failed */ cSize = (U32)srcSize; LZ4F_writeLE32(cSizePtr, cSize | LZ4F_BLOCKUNCOMPRESSED_FLAG); memcpy(cSizePtr+4, src, srcSize); } if (crcFlag) { U32 const crc32 = XXH32(cSizePtr+4, cSize, 0); /* checksum of compressed data */ LZ4F_writeLE32(cSizePtr+4+cSize, crc32); } return 4 + cSize + ((U32)crcFlag)*4; } static int LZ4F_compressBlock(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) { int const acceleration = (level < 0) ? -level + 1 : 1; LZ4F_initStream(ctx, cdict, level, LZ4F_blockIndependent); if (cdict) { return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration); } else { return LZ4_compress_fast_extState_fastReset(ctx, src, dst, srcSize, dstCapacity, acceleration); } } static int LZ4F_compressBlock_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) { int const acceleration = (level < 0) ? -level + 1 : 1; (void)cdict; /* init once at beginning of frame */ return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration); } static int LZ4F_compressBlockHC(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) { LZ4F_initStream(ctx, cdict, level, LZ4F_blockIndependent); if (cdict) { return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity); } return LZ4_compress_HC_extStateHC_fastReset(ctx, src, dst, srcSize, dstCapacity, level); } static int LZ4F_compressBlockHC_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict) { (void)level; (void)cdict; /* init once at beginning of frame */ return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity); } static compressFunc_t LZ4F_selectCompression(LZ4F_blockMode_t blockMode, int level) { if (level < LZ4HC_CLEVEL_MIN) { if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlock; return LZ4F_compressBlock_continue; } if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlockHC; return LZ4F_compressBlockHC_continue; } static int LZ4F_localSaveDict(LZ4F_cctx_t* cctxPtr) { if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) return LZ4_saveDict ((LZ4_stream_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB); return LZ4_saveDictHC ((LZ4_streamHC_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB); } typedef enum { notDone, fromTmpBuffer, fromSrcBuffer } LZ4F_lastBlockStatus; /*! LZ4F_compressUpdate() : * LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary. * dstBuffer MUST be >= LZ4F_compressBound(srcSize, preferencesPtr). * LZ4F_compressOptions_t structure is optional : you can provide NULL as argument. * @return : the number of bytes written into dstBuffer. It can be zero, meaning input data was just buffered. * or an error code if it fails (which can be tested using LZ4F_isError()) */ size_t LZ4F_compressUpdate(LZ4F_cctx* cctxPtr, void* dstBuffer, size_t dstCapacity, const void* srcBuffer, size_t srcSize, const LZ4F_compressOptions_t* compressOptionsPtr) { LZ4F_compressOptions_t cOptionsNull; size_t const blockSize = cctxPtr->maxBlockSize; const BYTE* srcPtr = (const BYTE*)srcBuffer; const BYTE* const srcEnd = srcPtr + srcSize; BYTE* const dstStart = (BYTE*)dstBuffer; BYTE* dstPtr = dstStart; LZ4F_lastBlockStatus lastBlockCompressed = notDone; compressFunc_t const compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel); DEBUGLOG(4, "LZ4F_compressUpdate (srcSize=%zu)", srcSize); if (cctxPtr->cStage != 1) return err0r(LZ4F_ERROR_GENERIC); if (dstCapacity < LZ4F_compressBound_internal(srcSize, &(cctxPtr->prefs), cctxPtr->tmpInSize)) return err0r(LZ4F_ERROR_dstMaxSize_tooSmall); MEM_INIT(&cOptionsNull, 0, sizeof(cOptionsNull)); if (compressOptionsPtr == NULL) compressOptionsPtr = &cOptionsNull; /* complete tmp buffer */ if (cctxPtr->tmpInSize > 0) { /* some data already within tmp buffer */ size_t const sizeToCopy = blockSize - cctxPtr->tmpInSize; if (sizeToCopy > srcSize) { /* add src to tmpIn buffer */ memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, srcSize); srcPtr = srcEnd; cctxPtr->tmpInSize += srcSize; /* still needs some CRC */ } else { /* complete tmpIn block and then compress it */ lastBlockCompressed = fromTmpBuffer; memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, sizeToCopy); srcPtr += sizeToCopy; dstPtr += LZ4F_makeBlock(dstPtr, cctxPtr->tmpIn, blockSize, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, cctxPtr->cdict, cctxPtr->prefs.frameInfo.blockChecksumFlag); if (cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) cctxPtr->tmpIn += blockSize; cctxPtr->tmpInSize = 0; } } while ((size_t)(srcEnd - srcPtr) >= blockSize) { /* compress full blocks */ lastBlockCompressed = fromSrcBuffer; dstPtr += LZ4F_makeBlock(dstPtr, srcPtr, blockSize, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, cctxPtr->cdict, cctxPtr->prefs.frameInfo.blockChecksumFlag); srcPtr += blockSize; } if ((cctxPtr->prefs.autoFlush) && (srcPtr < srcEnd)) { /* compress remaining input < blockSize */ lastBlockCompressed = fromSrcBuffer; dstPtr += LZ4F_makeBlock(dstPtr, srcPtr, srcEnd - srcPtr, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, cctxPtr->cdict, cctxPtr->prefs.frameInfo.blockChecksumFlag); srcPtr = srcEnd; } /* preserve dictionary if necessary */ if ((cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) && (lastBlockCompressed==fromSrcBuffer)) { if (compressOptionsPtr->stableSrc) { cctxPtr->tmpIn = cctxPtr->tmpBuff; } else { int const realDictSize = LZ4F_localSaveDict(cctxPtr); if (realDictSize==0) return err0r(LZ4F_ERROR_GENERIC); cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize; } } /* keep tmpIn within limits */ if ((cctxPtr->tmpIn + blockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize) /* necessarily LZ4F_blockLinked && lastBlockCompressed==fromTmpBuffer */ && !(cctxPtr->prefs.autoFlush)) { int const realDictSize = LZ4F_localSaveDict(cctxPtr); cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize; } /* some input data left, necessarily < blockSize */ if (srcPtr < srcEnd) { /* fill tmp buffer */ size_t const sizeToCopy = srcEnd - srcPtr; memcpy(cctxPtr->tmpIn, srcPtr, sizeToCopy); cctxPtr->tmpInSize = sizeToCopy; } if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled) XXH32_update(&(cctxPtr->xxh), srcBuffer, srcSize); cctxPtr->totalInSize += srcSize; return dstPtr - dstStart; } /*! LZ4F_flush() : * Should you need to create compressed data immediately, without waiting for a block to be filled, * you can call LZ4_flush(), which will immediately compress any remaining data stored within compressionContext. * The result of the function is the number of bytes written into dstBuffer * (it can be zero, this means there was no data left within compressionContext) * The function outputs an error code if it fails (can be tested using LZ4F_isError()) * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument. */ size_t LZ4F_flush(LZ4F_cctx* cctxPtr, void* dstBuffer, size_t dstCapacity, const LZ4F_compressOptions_t* compressOptionsPtr) { BYTE* const dstStart = (BYTE*)dstBuffer; BYTE* dstPtr = dstStart; compressFunc_t compress; if (cctxPtr->tmpInSize == 0) return 0; /* nothing to flush */ if (cctxPtr->cStage != 1) return err0r(LZ4F_ERROR_GENERIC); if (dstCapacity < (cctxPtr->tmpInSize + 4)) return err0r(LZ4F_ERROR_dstMaxSize_tooSmall); /* +4 : block header(4) */ (void)compressOptionsPtr; /* not yet useful */ /* select compression function */ compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel); /* compress tmp buffer */ dstPtr += LZ4F_makeBlock(dstPtr, cctxPtr->tmpIn, cctxPtr->tmpInSize, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel, cctxPtr->cdict, cctxPtr->prefs.frameInfo.blockChecksumFlag); if (cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) cctxPtr->tmpIn += cctxPtr->tmpInSize; cctxPtr->tmpInSize = 0; /* keep tmpIn within limits */ if ((cctxPtr->tmpIn + cctxPtr->maxBlockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize)) { /* necessarily LZ4F_blockLinked */ int realDictSize = LZ4F_localSaveDict(cctxPtr); cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize; } return dstPtr - dstStart; } /*! LZ4F_compressEnd() : * When you want to properly finish the compressed frame, just call LZ4F_compressEnd(). * It will flush whatever data remained within compressionContext (like LZ4_flush()) * but also properly finalize the frame, with an endMark and a checksum. * The result of the function is the number of bytes written into dstBuffer (necessarily >= 4 (endMark size)) * The function outputs an error code if it fails (can be tested using LZ4F_isError()) * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument. * compressionContext can then be used again, starting with LZ4F_compressBegin(). The preferences will remain the same. */ size_t LZ4F_compressEnd(LZ4F_cctx* cctxPtr, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr) { BYTE* const dstStart = (BYTE*)dstBuffer; BYTE* dstPtr = dstStart; size_t const flushSize = LZ4F_flush(cctxPtr, dstBuffer, dstMaxSize, compressOptionsPtr); if (LZ4F_isError(flushSize)) return flushSize; dstPtr += flushSize; LZ4F_writeLE32(dstPtr, 0); dstPtr+=4; /* endMark */ if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled) { U32 const xxh = XXH32_digest(&(cctxPtr->xxh)); LZ4F_writeLE32(dstPtr, xxh); dstPtr+=4; /* content Checksum */ } cctxPtr->cStage = 0; /* state is now re-usable (with identical preferences) */ cctxPtr->maxBufferSize = 0; /* reuse HC context */ if (cctxPtr->prefs.frameInfo.contentSize) { if (cctxPtr->prefs.frameInfo.contentSize != cctxPtr->totalInSize) return err0r(LZ4F_ERROR_frameSize_wrong); } return dstPtr - dstStart; } /*-*************************************************** * Frame Decompression *****************************************************/ typedef enum { dstage_getFrameHeader=0, dstage_storeFrameHeader, dstage_init, dstage_getBlockHeader, dstage_storeBlockHeader, dstage_copyDirect, dstage_getBlockChecksum, dstage_getCBlock, dstage_storeCBlock, dstage_flushOut, dstage_getSuffix, dstage_storeSuffix, dstage_getSFrameSize, dstage_storeSFrameSize, dstage_skipSkippable } dStage_t; struct LZ4F_dctx_s { LZ4F_frameInfo_t frameInfo; U32 version; dStage_t dStage; U64 frameRemainingSize; size_t maxBlockSize; size_t maxBufferSize; BYTE* tmpIn; size_t tmpInSize; size_t tmpInTarget; BYTE* tmpOutBuffer; const BYTE* dict; size_t dictSize; BYTE* tmpOut; size_t tmpOutSize; size_t tmpOutStart; XXH32_state_t xxh; XXH32_state_t blockChecksum; BYTE header[LZ4F_HEADER_SIZE_MAX]; }; /* typedef'd to LZ4F_dctx in lz4frame.h */ /*! LZ4F_createDecompressionContext() : * Create a decompressionContext object, which will track all decompression operations. * Provides a pointer to a fully allocated and initialized LZ4F_decompressionContext object. * Object can later be released using LZ4F_freeDecompressionContext(). * @return : if != 0, there was an error during context creation. */ LZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_dctx** LZ4F_decompressionContextPtr, unsigned versionNumber) { LZ4F_dctx* const dctx = (LZ4F_dctx*)ALLOC_AND_ZERO(sizeof(LZ4F_dctx)); if (dctx==NULL) return err0r(LZ4F_ERROR_GENERIC); dctx->version = versionNumber; *LZ4F_decompressionContextPtr = dctx; return LZ4F_OK_NoError; } LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx) { LZ4F_errorCode_t result = LZ4F_OK_NoError; if (dctx != NULL) { /* can accept NULL input, like free() */ result = (LZ4F_errorCode_t)dctx->dStage; FREEMEM(dctx->tmpIn); FREEMEM(dctx->tmpOutBuffer); FREEMEM(dctx); } return result; } /*==--- Streaming Decompression operations ---==*/ void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx) { dctx->dStage = dstage_getFrameHeader; dctx->dict = NULL; dctx->dictSize = 0; } /*! LZ4F_headerSize() : * @return : size of frame header * or an error code, which can be tested using LZ4F_isError() */ static size_t LZ4F_headerSize(const void* src, size_t srcSize) { /* minimal srcSize to determine header size */ if (srcSize < 5) return err0r(LZ4F_ERROR_frameHeader_incomplete); /* special case : skippable frames */ if ((LZ4F_readLE32(src) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START) return 8; /* control magic number */ if (LZ4F_readLE32(src) != LZ4F_MAGICNUMBER) return err0r(LZ4F_ERROR_frameType_unknown); /* Frame Header Size */ { BYTE const FLG = ((const BYTE*)src)[4]; U32 const contentSizeFlag = (FLG>>3) & _1BIT; U32 const dictIDFlag = FLG & _1BIT; return minFHSize + (contentSizeFlag*8) + (dictIDFlag*4); } } /*! LZ4F_decodeHeader() : * input : `src` points at the **beginning of the frame** * output : set internal values of dctx, such as * dctx->frameInfo and dctx->dStage. * Also allocates internal buffers. * @return : nb Bytes read from src (necessarily <= srcSize) * or an error code (testable with LZ4F_isError()) */ static size_t LZ4F_decodeHeader(LZ4F_dctx* dctx, const void* src, size_t srcSize) { unsigned blockMode, blockChecksumFlag, contentSizeFlag, contentChecksumFlag, dictIDFlag, blockSizeID; size_t frameHeaderSize; const BYTE* srcPtr = (const BYTE*)src; /* need to decode header to get frameInfo */ if (srcSize < minFHSize) return err0r(LZ4F_ERROR_frameHeader_incomplete); /* minimal frame header size */ MEM_INIT(&(dctx->frameInfo), 0, sizeof(dctx->frameInfo)); /* special case : skippable frames */ if ((LZ4F_readLE32(srcPtr) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START) { dctx->frameInfo.frameType = LZ4F_skippableFrame; if (src == (void*)(dctx->header)) { dctx->tmpInSize = srcSize; dctx->tmpInTarget = 8; dctx->dStage = dstage_storeSFrameSize; return srcSize; } else { dctx->dStage = dstage_getSFrameSize; return 4; } } /* control magic number */ if (LZ4F_readLE32(srcPtr) != LZ4F_MAGICNUMBER) return err0r(LZ4F_ERROR_frameType_unknown); dctx->frameInfo.frameType = LZ4F_frame; /* Flags */ { U32 const FLG = srcPtr[4]; U32 const version = (FLG>>6) & _2BITS; blockChecksumFlag = (FLG>>4) & _1BIT; blockMode = (FLG>>5) & _1BIT; contentSizeFlag = (FLG>>3) & _1BIT; contentChecksumFlag = (FLG>>2) & _1BIT; dictIDFlag = FLG & _1BIT; /* validate */ if (((FLG>>1)&_1BIT) != 0) return err0r(LZ4F_ERROR_reservedFlag_set); /* Reserved bit */ if (version != 1) return err0r(LZ4F_ERROR_headerVersion_wrong); /* Version Number, only supported value */ } /* Frame Header Size */ frameHeaderSize = minFHSize + (contentSizeFlag*8) + (dictIDFlag*4); if (srcSize < frameHeaderSize) { /* not enough input to fully decode frame header */ if (srcPtr != dctx->header) memcpy(dctx->header, srcPtr, srcSize); dctx->tmpInSize = srcSize; dctx->tmpInTarget = frameHeaderSize; dctx->dStage = dstage_storeFrameHeader; return srcSize; } { U32 const BD = srcPtr[5]; blockSizeID = (BD>>4) & _3BITS; /* validate */ if (((BD>>7)&_1BIT) != 0) return err0r(LZ4F_ERROR_reservedFlag_set); /* Reserved bit */ if (blockSizeID < 4) return err0r(LZ4F_ERROR_maxBlockSize_invalid); /* 4-7 only supported values for the time being */ if (((BD>>0)&_4BITS) != 0) return err0r(LZ4F_ERROR_reservedFlag_set); /* Reserved bits */ } /* check header */ { BYTE const HC = LZ4F_headerChecksum(srcPtr+4, frameHeaderSize-5); if (HC != srcPtr[frameHeaderSize-1]) return err0r(LZ4F_ERROR_headerChecksum_invalid); } /* save */ dctx->frameInfo.blockMode = (LZ4F_blockMode_t)blockMode; dctx->frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)blockChecksumFlag; dctx->frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)contentChecksumFlag; dctx->frameInfo.blockSizeID = (LZ4F_blockSizeID_t)blockSizeID; dctx->maxBlockSize = LZ4F_getBlockSize(blockSizeID); if (contentSizeFlag) dctx->frameRemainingSize = dctx->frameInfo.contentSize = LZ4F_readLE64(srcPtr+6); if (dictIDFlag) dctx->frameInfo.dictID = LZ4F_readLE32(srcPtr + frameHeaderSize - 5); dctx->dStage = dstage_init; return frameHeaderSize; } /*! LZ4F_getFrameInfo() : * This function extracts frame parameters (max blockSize, frame checksum, etc.). * Usage is optional. Objective is to provide relevant information for allocation purposes. * This function works in 2 situations : * - At the beginning of a new frame, in which case it will decode this information from `srcBuffer`, and start the decoding process. * Amount of input data provided must be large enough to successfully decode the frame header. * A header size is variable, but is guaranteed to be <= LZ4F_HEADER_SIZE_MAX bytes. It's possible to provide more input data than this minimum. * - After decoding has been started. In which case, no input is read, frame parameters are extracted from dctx. * The number of bytes consumed from srcBuffer will be updated within *srcSizePtr (necessarily <= original value). * Decompression must resume from (srcBuffer + *srcSizePtr). * @return : an hint about how many srcSize bytes LZ4F_decompress() expects for next call, * or an error code which can be tested using LZ4F_isError() * note 1 : in case of error, dctx is not modified. Decoding operations can resume from where they stopped. * note 2 : frame parameters are *copied into* an already allocated LZ4F_frameInfo_t structure. */ LZ4F_errorCode_t LZ4F_getFrameInfo(LZ4F_dctx* dctx, LZ4F_frameInfo_t* frameInfoPtr, const void* srcBuffer, size_t* srcSizePtr) { if (dctx->dStage > dstage_storeFrameHeader) { /* assumption : dstage_* header enum at beginning of range */ /* frameInfo already decoded */ size_t o=0, i=0; *srcSizePtr = 0; *frameInfoPtr = dctx->frameInfo; /* returns : recommended nb of bytes for LZ4F_decompress() */ return LZ4F_decompress(dctx, NULL, &o, NULL, &i, NULL); } else { if (dctx->dStage == dstage_storeFrameHeader) { /* frame decoding already started, in the middle of header => automatic fail */ *srcSizePtr = 0; return err0r(LZ4F_ERROR_frameDecoding_alreadyStarted); } else { size_t decodeResult; size_t const hSize = LZ4F_headerSize(srcBuffer, *srcSizePtr); if (LZ4F_isError(hSize)) { *srcSizePtr=0; return hSize; } if (*srcSizePtr < hSize) { *srcSizePtr=0; return err0r(LZ4F_ERROR_frameHeader_incomplete); } decodeResult = LZ4F_decodeHeader(dctx, srcBuffer, hSize); if (LZ4F_isError(decodeResult)) { *srcSizePtr = 0; } else { *srcSizePtr = decodeResult; decodeResult = BHSize; /* block header size */ } *frameInfoPtr = dctx->frameInfo; return decodeResult; } } } /* LZ4F_updateDict() : * only used for LZ4F_blockLinked mode */ static void LZ4F_updateDict(LZ4F_dctx* dctx, const BYTE* dstPtr, size_t dstSize, const BYTE* dstBufferStart, unsigned withinTmp) { if (dctx->dictSize==0) dctx->dict = (const BYTE*)dstPtr; /* priority to dictionary continuity */ if (dctx->dict + dctx->dictSize == dstPtr) { /* dictionary continuity, directly within dstBuffer */ dctx->dictSize += dstSize; return; } if (dstPtr - dstBufferStart + dstSize >= 64 KB) { /* history in dstBuffer becomes large enough to become dictionary */ dctx->dict = (const BYTE*)dstBufferStart; dctx->dictSize = dstPtr - dstBufferStart + dstSize; return; } assert(dstSize < 64 KB); /* if dstSize >= 64 KB, dictionary would be set into dstBuffer directly */ /* dstBuffer does not contain whole useful history (64 KB), so it must be saved within tmpOut */ if ((withinTmp) && (dctx->dict == dctx->tmpOutBuffer)) { /* continue history within tmpOutBuffer */ /* withinTmp expectation : content of [dstPtr,dstSize] is same as [dict+dictSize,dstSize], so we just extend it */ assert(dctx->dict + dctx->dictSize == dctx->tmpOut + dctx->tmpOutStart); dctx->dictSize += dstSize; return; } if (withinTmp) { /* copy relevant dict portion in front of tmpOut within tmpOutBuffer */ size_t const preserveSize = dctx->tmpOut - dctx->tmpOutBuffer; size_t copySize = 64 KB - dctx->tmpOutSize; const BYTE* const oldDictEnd = dctx->dict + dctx->dictSize - dctx->tmpOutStart; if (dctx->tmpOutSize > 64 KB) copySize = 0; if (copySize > preserveSize) copySize = preserveSize; memcpy(dctx->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize); dctx->dict = dctx->tmpOutBuffer; dctx->dictSize = preserveSize + dctx->tmpOutStart + dstSize; return; } if (dctx->dict == dctx->tmpOutBuffer) { /* copy dst into tmp to complete dict */ if (dctx->dictSize + dstSize > dctx->maxBufferSize) { /* tmp buffer not large enough */ size_t const preserveSize = 64 KB - dstSize; memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize); dctx->dictSize = preserveSize; } memcpy(dctx->tmpOutBuffer + dctx->dictSize, dstPtr, dstSize); dctx->dictSize += dstSize; return; } /* join dict & dest into tmp */ { size_t preserveSize = 64 KB - dstSize; if (preserveSize > dctx->dictSize) preserveSize = dctx->dictSize; memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize); memcpy(dctx->tmpOutBuffer + preserveSize, dstPtr, dstSize); dctx->dict = dctx->tmpOutBuffer; dctx->dictSize = preserveSize + dstSize; } } /*! LZ4F_decompress() : * Call this function repetitively to regenerate compressed data in srcBuffer. * The function will attempt to decode up to *srcSizePtr bytes from srcBuffer * into dstBuffer of capacity *dstSizePtr. * * The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value). * * The number of bytes effectively read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value). * If number of bytes read is < number of bytes provided, then decompression operation is not complete. * Remaining data will have to be presented again in a subsequent invocation. * * The function result is an hint of the better srcSize to use for next call to LZ4F_decompress. * Schematically, it's the size of the current (or remaining) compressed block + header of next block. * Respecting the hint provides a small boost to performance, since it allows less buffer shuffling. * Note that this is just a hint, and it's always possible to any srcSize value. * When a frame is fully decoded, @return will be 0. * If decompression failed, @return is an error code which can be tested using LZ4F_isError(). */ size_t LZ4F_decompress(LZ4F_dctx* dctx, void* dstBuffer, size_t* dstSizePtr, const void* srcBuffer, size_t* srcSizePtr, const LZ4F_decompressOptions_t* decompressOptionsPtr) { LZ4F_decompressOptions_t optionsNull; const BYTE* const srcStart = (const BYTE*)srcBuffer; const BYTE* const srcEnd = srcStart + *srcSizePtr; const BYTE* srcPtr = srcStart; BYTE* const dstStart = (BYTE*)dstBuffer; BYTE* const dstEnd = dstStart + *dstSizePtr; BYTE* dstPtr = dstStart; const BYTE* selectedIn = NULL; unsigned doAnotherStage = 1; size_t nextSrcSizeHint = 1; MEM_INIT(&optionsNull, 0, sizeof(optionsNull)); if (decompressOptionsPtr==NULL) decompressOptionsPtr = &optionsNull; *srcSizePtr = 0; *dstSizePtr = 0; /* behaves as a state machine */ while (doAnotherStage) { switch(dctx->dStage) { case dstage_getFrameHeader: if ((size_t)(srcEnd-srcPtr) >= maxFHSize) { /* enough to decode - shortcut */ size_t const hSize = LZ4F_decodeHeader(dctx, srcPtr, srcEnd-srcPtr); /* will update dStage appropriately */ if (LZ4F_isError(hSize)) return hSize; srcPtr += hSize; break; } dctx->tmpInSize = 0; if (srcEnd-srcPtr == 0) return minFHSize; /* 0-size input */ dctx->tmpInTarget = minFHSize; /* minimum size to decode header */ dctx->dStage = dstage_storeFrameHeader; /* fall-through */ case dstage_storeFrameHeader: { size_t const sizeToCopy = MIN(dctx->tmpInTarget - dctx->tmpInSize, (size_t)(srcEnd - srcPtr)); memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy); dctx->tmpInSize += sizeToCopy; srcPtr += sizeToCopy; } if (dctx->tmpInSize < dctx->tmpInTarget) { nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize) + BHSize; /* rest of header + nextBlockHeader */ doAnotherStage = 0; /* not enough src data, ask for some more */ break; } { size_t const hSize = LZ4F_decodeHeader(dctx, dctx->header, dctx->tmpInTarget); /* will update dStage appropriately */ if (LZ4F_isError(hSize)) return hSize; } break; case dstage_init: if (dctx->frameInfo.contentChecksumFlag) XXH32_reset(&(dctx->xxh), 0); /* internal buffers allocation */ { size_t const bufferNeeded = dctx->maxBlockSize + ((dctx->frameInfo.blockMode==LZ4F_blockLinked) * 128 KB); if (bufferNeeded > dctx->maxBufferSize) { /* tmp buffers too small */ dctx->maxBufferSize = 0; /* ensure allocation will be re-attempted on next entry*/ FREEMEM(dctx->tmpIn); dctx->tmpIn = (BYTE*)ALLOC(dctx->maxBlockSize + 4 /* block checksum */); if (dctx->tmpIn == NULL) return err0r(LZ4F_ERROR_allocation_failed); FREEMEM(dctx->tmpOutBuffer); dctx->tmpOutBuffer= (BYTE*)ALLOC(bufferNeeded); if (dctx->tmpOutBuffer== NULL) return err0r(LZ4F_ERROR_allocation_failed); dctx->maxBufferSize = bufferNeeded; } } dctx->tmpInSize = 0; dctx->tmpInTarget = 0; dctx->tmpOut = dctx->tmpOutBuffer; dctx->tmpOutStart = 0; dctx->tmpOutSize = 0; dctx->dStage = dstage_getBlockHeader; /* fall-through */ case dstage_getBlockHeader: if ((size_t)(srcEnd - srcPtr) >= BHSize) { selectedIn = srcPtr; srcPtr += BHSize; } else { /* not enough input to read cBlockSize field */ dctx->tmpInSize = 0; dctx->dStage = dstage_storeBlockHeader; } if (dctx->dStage == dstage_storeBlockHeader) /* can be skipped */ case dstage_storeBlockHeader: { size_t const remainingInput = (size_t)(srcEnd - srcPtr); size_t const wantedData = BHSize - dctx->tmpInSize; size_t const sizeToCopy = MIN(wantedData, remainingInput); memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy); srcPtr += sizeToCopy; dctx->tmpInSize += sizeToCopy; if (dctx->tmpInSize < BHSize) { /* not enough input for cBlockSize */ nextSrcSizeHint = BHSize - dctx->tmpInSize; doAnotherStage = 0; break; } selectedIn = dctx->tmpIn; } /* if (dctx->dStage == dstage_storeBlockHeader) */ /* decode block header */ { size_t const nextCBlockSize = LZ4F_readLE32(selectedIn) & 0x7FFFFFFFU; size_t const crcSize = dctx->frameInfo.blockChecksumFlag * 4; if (nextCBlockSize==0) { /* frameEnd signal, no more block */ dctx->dStage = dstage_getSuffix; break; } if (nextCBlockSize > dctx->maxBlockSize) return err0r(LZ4F_ERROR_maxBlockSize_invalid); if (LZ4F_readLE32(selectedIn) & LZ4F_BLOCKUNCOMPRESSED_FLAG) { /* next block is uncompressed */ dctx->tmpInTarget = nextCBlockSize; if (dctx->frameInfo.blockChecksumFlag) { XXH32_reset(&dctx->blockChecksum, 0); } dctx->dStage = dstage_copyDirect; break; } /* next block is a compressed block */ dctx->tmpInTarget = nextCBlockSize + crcSize; dctx->dStage = dstage_getCBlock; if (dstPtr==dstEnd) { nextSrcSizeHint = nextCBlockSize + crcSize + BHSize; doAnotherStage = 0; } break; } case dstage_copyDirect: /* uncompressed block */ { size_t const minBuffSize = MIN((size_t)(srcEnd-srcPtr), (size_t)(dstEnd-dstPtr)); size_t const sizeToCopy = MIN(dctx->tmpInTarget, minBuffSize); memcpy(dstPtr, srcPtr, sizeToCopy); if (dctx->frameInfo.blockChecksumFlag) { XXH32_update(&dctx->blockChecksum, srcPtr, sizeToCopy); } if (dctx->frameInfo.contentChecksumFlag) XXH32_update(&dctx->xxh, srcPtr, sizeToCopy); if (dctx->frameInfo.contentSize) dctx->frameRemainingSize -= sizeToCopy; /* history management (linked blocks only)*/ if (dctx->frameInfo.blockMode == LZ4F_blockLinked) LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 0); srcPtr += sizeToCopy; dstPtr += sizeToCopy; if (sizeToCopy == dctx->tmpInTarget) { /* all done */ if (dctx->frameInfo.blockChecksumFlag) { dctx->tmpInSize = 0; dctx->dStage = dstage_getBlockChecksum; } else dctx->dStage = dstage_getBlockHeader; /* new block */ break; } dctx->tmpInTarget -= sizeToCopy; /* need to copy more */ nextSrcSizeHint = dctx->tmpInTarget + + dctx->frameInfo.contentChecksumFlag * 4 /* block checksum */ + BHSize /* next header size */; doAnotherStage = 0; break; } /* check block checksum for recently transferred uncompressed block */ case dstage_getBlockChecksum: { const void* crcSrc; if ((srcEnd-srcPtr >= 4) && (dctx->tmpInSize==0)) { crcSrc = srcPtr; srcPtr += 4; } else { size_t const stillToCopy = 4 - dctx->tmpInSize; size_t const sizeToCopy = MIN(stillToCopy, (size_t)(srcEnd-srcPtr)); memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy); dctx->tmpInSize += sizeToCopy; srcPtr += sizeToCopy; if (dctx->tmpInSize < 4) { /* all input consumed */ doAnotherStage = 0; break; } crcSrc = dctx->header; } { U32 const readCRC = LZ4F_readLE32(crcSrc); U32 const calcCRC = XXH32_digest(&dctx->blockChecksum); if (readCRC != calcCRC) return err0r(LZ4F_ERROR_blockChecksum_invalid); } } dctx->dStage = dstage_getBlockHeader; /* new block */ break; case dstage_getCBlock: if ((size_t)(srcEnd-srcPtr) < dctx->tmpInTarget) { dctx->tmpInSize = 0; dctx->dStage = dstage_storeCBlock; break; } /* input large enough to read full block directly */ selectedIn = srcPtr; srcPtr += dctx->tmpInTarget; if (0) /* jump over next block */ case dstage_storeCBlock: { size_t const wantedData = dctx->tmpInTarget - dctx->tmpInSize; size_t const inputLeft = (size_t)(srcEnd-srcPtr); size_t const sizeToCopy = MIN(wantedData, inputLeft); memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy); dctx->tmpInSize += sizeToCopy; srcPtr += sizeToCopy; if (dctx->tmpInSize < dctx->tmpInTarget) { /* need more input */ nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize) + BHSize; doAnotherStage=0; break; } selectedIn = dctx->tmpIn; } /* At this stage, input is large enough to decode a block */ if (dctx->frameInfo.blockChecksumFlag) { dctx->tmpInTarget -= 4; assert(selectedIn != NULL); /* selectedIn is defined at this stage (either srcPtr, or dctx->tmpIn) */ { U32 const readBlockCrc = LZ4F_readLE32(selectedIn + dctx->tmpInTarget); U32 const calcBlockCrc = XXH32(selectedIn, dctx->tmpInTarget, 0); if (readBlockCrc != calcBlockCrc) return err0r(LZ4F_ERROR_blockChecksum_invalid); } } if ((size_t)(dstEnd-dstPtr) >= dctx->maxBlockSize) { const char* dict = (const char*)dctx->dict; size_t dictSize = dctx->dictSize; int decodedSize; if (dict && dictSize > 1 GB) { /* the dictSize param is an int, avoid truncation / sign issues */ dict += dictSize - 64 KB; dictSize = 64 KB; } /* enough capacity in `dst` to decompress directly there */ decodedSize = LZ4_decompress_safe_usingDict( (const char*)selectedIn, (char*)dstPtr, (int)dctx->tmpInTarget, (int)dctx->maxBlockSize, dict, (int)dictSize); if (decodedSize < 0) return err0r(LZ4F_ERROR_GENERIC); /* decompression failed */ if (dctx->frameInfo.contentChecksumFlag) XXH32_update(&(dctx->xxh), dstPtr, decodedSize); if (dctx->frameInfo.contentSize) dctx->frameRemainingSize -= decodedSize; /* dictionary management */ if (dctx->frameInfo.blockMode==LZ4F_blockLinked) LZ4F_updateDict(dctx, dstPtr, decodedSize, dstStart, 0); dstPtr += decodedSize; dctx->dStage = dstage_getBlockHeader; break; } /* not enough place into dst : decode into tmpOut */ /* ensure enough place for tmpOut */ if (dctx->frameInfo.blockMode == LZ4F_blockLinked) { if (dctx->dict == dctx->tmpOutBuffer) { if (dctx->dictSize > 128 KB) { memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - 64 KB, 64 KB); dctx->dictSize = 64 KB; } dctx->tmpOut = dctx->tmpOutBuffer + dctx->dictSize; } else { /* dict not within tmp */ size_t const reservedDictSpace = MIN(dctx->dictSize, 64 KB); dctx->tmpOut = dctx->tmpOutBuffer + reservedDictSpace; } } /* Decode block */ { const char* dict = (const char*)dctx->dict; size_t dictSize = dctx->dictSize; int decodedSize; if (dict && dictSize > 1 GB) { /* the dictSize param is an int, avoid truncation / sign issues */ dict += dictSize - 64 KB; dictSize = 64 KB; } decodedSize = LZ4_decompress_safe_usingDict( (const char*)selectedIn, (char*)dctx->tmpOut, (int)dctx->tmpInTarget, (int)dctx->maxBlockSize, dict, (int)dictSize); if (decodedSize < 0) /* decompression failed */ return err0r(LZ4F_ERROR_decompressionFailed); if (dctx->frameInfo.contentChecksumFlag) XXH32_update(&(dctx->xxh), dctx->tmpOut, decodedSize); if (dctx->frameInfo.contentSize) dctx->frameRemainingSize -= decodedSize; dctx->tmpOutSize = decodedSize; dctx->tmpOutStart = 0; dctx->dStage = dstage_flushOut; } /* fall-through */ case dstage_flushOut: /* flush decoded data from tmpOut to dstBuffer */ { size_t const sizeToCopy = MIN(dctx->tmpOutSize - dctx->tmpOutStart, (size_t)(dstEnd-dstPtr)); memcpy(dstPtr, dctx->tmpOut + dctx->tmpOutStart, sizeToCopy); /* dictionary management */ if (dctx->frameInfo.blockMode == LZ4F_blockLinked) LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 1 /*withinTmp*/); dctx->tmpOutStart += sizeToCopy; dstPtr += sizeToCopy; if (dctx->tmpOutStart == dctx->tmpOutSize) { /* all flushed */ dctx->dStage = dstage_getBlockHeader; /* get next block */ break; } /* could not flush everything : stop there, just request a block header */ doAnotherStage = 0; nextSrcSizeHint = BHSize; break; } case dstage_getSuffix: if (dctx->frameRemainingSize) return err0r(LZ4F_ERROR_frameSize_wrong); /* incorrect frame size decoded */ if (!dctx->frameInfo.contentChecksumFlag) { /* no checksum, frame is completed */ nextSrcSizeHint = 0; LZ4F_resetDecompressionContext(dctx); doAnotherStage = 0; break; } if ((srcEnd - srcPtr) < 4) { /* not enough size for entire CRC */ dctx->tmpInSize = 0; dctx->dStage = dstage_storeSuffix; } else { selectedIn = srcPtr; srcPtr += 4; } if (dctx->dStage == dstage_storeSuffix) /* can be skipped */ case dstage_storeSuffix: { size_t const remainingInput = (size_t)(srcEnd - srcPtr); size_t const wantedData = 4 - dctx->tmpInSize; size_t const sizeToCopy = MIN(wantedData, remainingInput); memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy); srcPtr += sizeToCopy; dctx->tmpInSize += sizeToCopy; if (dctx->tmpInSize < 4) { /* not enough input to read complete suffix */ nextSrcSizeHint = 4 - dctx->tmpInSize; doAnotherStage=0; break; } selectedIn = dctx->tmpIn; } /* if (dctx->dStage == dstage_storeSuffix) */ /* case dstage_checkSuffix: */ /* no direct entry, avoid initialization risks */ { U32 const readCRC = LZ4F_readLE32(selectedIn); U32 const resultCRC = XXH32_digest(&(dctx->xxh)); if (readCRC != resultCRC) return err0r(LZ4F_ERROR_contentChecksum_invalid); nextSrcSizeHint = 0; LZ4F_resetDecompressionContext(dctx); doAnotherStage = 0; break; } case dstage_getSFrameSize: if ((srcEnd - srcPtr) >= 4) { selectedIn = srcPtr; srcPtr += 4; } else { /* not enough input to read cBlockSize field */ dctx->tmpInSize = 4; dctx->tmpInTarget = 8; dctx->dStage = dstage_storeSFrameSize; } if (dctx->dStage == dstage_storeSFrameSize) case dstage_storeSFrameSize: { size_t const sizeToCopy = MIN(dctx->tmpInTarget - dctx->tmpInSize, (size_t)(srcEnd - srcPtr) ); memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy); srcPtr += sizeToCopy; dctx->tmpInSize += sizeToCopy; if (dctx->tmpInSize < dctx->tmpInTarget) { /* not enough input to get full sBlockSize; wait for more */ nextSrcSizeHint = dctx->tmpInTarget - dctx->tmpInSize; doAnotherStage = 0; break; } selectedIn = dctx->header + 4; } /* if (dctx->dStage == dstage_storeSFrameSize) */ /* case dstage_decodeSFrameSize: */ /* no direct entry */ { size_t const SFrameSize = LZ4F_readLE32(selectedIn); dctx->frameInfo.contentSize = SFrameSize; dctx->tmpInTarget = SFrameSize; dctx->dStage = dstage_skipSkippable; break; } case dstage_skipSkippable: { size_t const skipSize = MIN(dctx->tmpInTarget, (size_t)(srcEnd-srcPtr)); srcPtr += skipSize; dctx->tmpInTarget -= skipSize; doAnotherStage = 0; nextSrcSizeHint = dctx->tmpInTarget; if (nextSrcSizeHint) break; /* still more to skip */ /* frame fully skipped : prepare context for a new frame */ LZ4F_resetDecompressionContext(dctx); break; } } /* switch (dctx->dStage) */ } /* while (doAnotherStage) */ /* preserve history within tmp whenever necessary */ LZ4F_STATIC_ASSERT((unsigned)dstage_init == 2); if ( (dctx->frameInfo.blockMode==LZ4F_blockLinked) /* next block will use up to 64KB from previous ones */ && (dctx->dict != dctx->tmpOutBuffer) /* dictionary is not already within tmp */ && (!decompressOptionsPtr->stableDst) /* cannot rely on dst data to remain there for next call */ && ((unsigned)(dctx->dStage)-2 < (unsigned)(dstage_getSuffix)-2) ) /* valid stages : [init ... getSuffix[ */ { if (dctx->dStage == dstage_flushOut) { size_t const preserveSize = dctx->tmpOut - dctx->tmpOutBuffer; size_t copySize = 64 KB - dctx->tmpOutSize; const BYTE* oldDictEnd = dctx->dict + dctx->dictSize - dctx->tmpOutStart; if (dctx->tmpOutSize > 64 KB) copySize = 0; if (copySize > preserveSize) copySize = preserveSize; if (copySize > 0) memcpy(dctx->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize); dctx->dict = dctx->tmpOutBuffer; dctx->dictSize = preserveSize + dctx->tmpOutStart; } else { const BYTE* const oldDictEnd = dctx->dict + dctx->dictSize; size_t const newDictSize = MIN(dctx->dictSize, 64 KB); if (newDictSize > 0) memcpy(dctx->tmpOutBuffer, oldDictEnd - newDictSize, newDictSize); dctx->dict = dctx->tmpOutBuffer; dctx->dictSize = newDictSize; dctx->tmpOut = dctx->tmpOutBuffer + newDictSize; } } *srcSizePtr = (srcPtr - srcStart); *dstSizePtr = (dstPtr - dstStart); return nextSrcSizeHint; } /*! LZ4F_decompress_usingDict() : * Same as LZ4F_decompress(), using a predefined dictionary. * Dictionary is used "in place", without any preprocessing. * It must remain accessible throughout the entire frame decoding. */ size_t LZ4F_decompress_usingDict(LZ4F_dctx* dctx, void* dstBuffer, size_t* dstSizePtr, const void* srcBuffer, size_t* srcSizePtr, const void* dict, size_t dictSize, const LZ4F_decompressOptions_t* decompressOptionsPtr) { if (dctx->dStage <= dstage_init) { dctx->dict = (const BYTE*)dict; dctx->dictSize = dictSize; } return LZ4F_decompress(dctx, dstBuffer, dstSizePtr, srcBuffer, srcSizePtr, decompressOptionsPtr); }
74,815
1,775
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/platform.h
/* clang-format off */ /* platform.h - compiler and OS detection Copyright (C) 2016-present, Przemyslaw Skibinski, Yann Collet This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef PLATFORM_H_MODULE #define PLATFORM_H_MODULE #if defined (__cplusplus) extern "C" { #endif /* ************************************** * Compiler Options ****************************************/ #if defined(_MSC_VER) # define _CRT_SECURE_NO_WARNINGS /* Disable Visual Studio warning messages for fopen, strncpy, strerror */ # if (_MSC_VER <= 1800) /* (1800 = Visual Studio 2013) */ # define _CRT_SECURE_NO_DEPRECATE /* VS2005 - must be declared before <io.h> and <windows.h> */ # define snprintf sprintf_s /* snprintf unsupported by Visual <= 2013 */ # endif #endif /* ************************************** * Detect 64-bit OS * http://nadeausoftware.com/articles/2012/02/c_c_tip_how_detect_processor_type_using_compiler_predefined_macros ****************************************/ #if defined __ia64 || defined _M_IA64 /* Intel Itanium */ \ || defined __powerpc64__ || defined __ppc64__ || defined __PPC64__ /* POWER 64-bit */ \ || (defined __sparc && (defined __sparcv9 || defined __sparc_v9__ || defined __arch64__)) || defined __sparc64__ /* SPARC 64-bit */ \ || defined __x86_64__s || defined _M_X64 /* x86 64-bit */ \ || defined __arm64__ || defined __aarch64__ || defined __ARM64_ARCH_8__ /* ARM 64-bit */ \ || (defined __mips && (__mips == 64 || __mips == 4 || __mips == 3)) /* MIPS 64-bit */ \ || defined _LP64 || defined __LP64__ /* NetBSD, OpenBSD */ || defined __64BIT__ /* AIX */ || defined _ADDR64 /* Cray */ \ || (defined __SIZEOF_POINTER__ && __SIZEOF_POINTER__ == 8) /* gcc */ # if !defined(__64BIT__) # define __64BIT__ 1 # endif #endif /* ********************************************************* * Turn on Large Files support (>4GB) for 32-bit Linux/Unix ***********************************************************/ #if !defined(__64BIT__) || defined(__MINGW32__) /* No point defining Large file for 64 bit but MinGW-w64 requires it */ # if !defined(_FILE_OFFSET_BITS) # define _FILE_OFFSET_BITS 64 /* turn off_t into a 64-bit type for ftello, fseeko */ # endif # if !defined(_LARGEFILE_SOURCE) /* obsolete macro, replaced with _FILE_OFFSET_BITS */ # define _LARGEFILE_SOURCE 1 /* Large File Support extension (LFS) - fseeko, ftello */ # endif # if defined(_AIX) || defined(__hpux) # define _LARGE_FILES /* Large file support on 32-bits AIX and HP-UX */ # endif #endif /* ************************************************************ * Detect POSIX version * PLATFORM_POSIX_VERSION = -1 for non-Unix e.g. Windows * PLATFORM_POSIX_VERSION = 0 for Unix-like non-POSIX * PLATFORM_POSIX_VERSION >= 1 is equal to found _POSIX_VERSION ***************************************************************/ #if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)) /* UNIX-like OS */ \ || defined(__midipix__) || defined(__VMS)) # if (defined(__APPLE__) && defined(__MACH__)) || defined(__SVR4) || defined(_AIX) || defined(__hpux) /* POSIX.1–2001 (SUSv3) conformant */ \ || defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__MidnightBSD__) /* BSD distros */ # define PLATFORM_POSIX_VERSION 200112L # else # if defined(__linux__) || defined(__linux) # ifndef _POSIX_C_SOURCE # define _POSIX_C_SOURCE 200112L /* use feature test macro */ # endif # endif # include "libc/calls/calls.h" /* declares _POSIX_VERSION (what?) */ # if defined(_POSIX_VERSION) /* POSIX compliant */ # define PLATFORM_POSIX_VERSION _POSIX_VERSION # else # define PLATFORM_POSIX_VERSION 0 # endif # endif #endif #if !defined(PLATFORM_POSIX_VERSION) # define PLATFORM_POSIX_VERSION -1 #endif /*-********************************************* * Detect if isatty() and fileno() are available ************************************************/ #if (defined(__linux__) && (PLATFORM_POSIX_VERSION >= 1)) || (PLATFORM_POSIX_VERSION >= 200112L) || defined(__DJGPP__) # define IS_CONSOLE(stdStream) isatty(fileno(stdStream)) #elif defined(MSDOS) || defined(OS2) || defined(__CYGWIN__) # define IS_CONSOLE(stdStream) _isatty(_fileno(stdStream)) #elif defined(WIN32) || defined(_WIN32) #include "libc/stdio/stdio.h" /* FILE */ static __inline int IS_CONSOLE(FILE* stdStream) { DWORD dummy; return _isatty(_fileno(stdStream)) && GetConsoleMode((HANDLE)_get_osfhandle(_fileno(stdStream)), &dummy); } #else # define IS_CONSOLE(stdStream) 0 #endif /****************************** * OS-specific Includes ******************************/ #if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(_WIN32) # if !defined(__DJGPP__) # define SET_BINARY_MODE(file) { int unused=_setmode(_fileno(file), _O_BINARY); (void)unused; } # define SET_SPARSE_FILE_MODE(file) { DWORD dw; DeviceIoControl((HANDLE) _get_osfhandle(_fileno(file)), FSCTL_SET_SPARSE, 0, 0, 0, 0, &dw, 0); } # else # define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) # define SET_SPARSE_FILE_MODE(file) # endif #else # define SET_BINARY_MODE(file) # define SET_SPARSE_FILE_MODE(file) #endif #if defined (__cplusplus) } #endif #endif /* PLATFORM_H_MODULE */
6,465
148
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/bench.h
/* clang-format off */ /* bench.h - Demo program to benchmark open-source compression algorithm Copyright (C) Yann Collet 2012-2016 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. You can contact the author at : - LZ4 source repository : https://github.com/lz4/lz4 - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c */ #ifndef BENCH_H_125623623633 #define BENCH_H_125623623633 int BMK_benchFiles(const char** fileNamesTable, unsigned nbFiles, int cLevel, int cLevelLast); /* Set Parameters */ void BMK_setNbSeconds(unsigned nbLoops); void BMK_setBlockSize(size_t blockSize); void BMK_setAdditionalParam(int additionalParam); void BMK_setNotificationLevel(unsigned level); void BMK_setBenchSeparately(int separate); #endif /* BENCH_H_125623623633 */
1,487
39
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/lz4cli.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ # # WARNING # # This is GPL program. It's intended for compressing files. # Cosmopolitan provides a 116 byte LZ4 runtime for extracting them. # Consider using that before linking this. # # SEE ALSO # # libc/nexgen32e/lz4cpy.c PKGS += THIRD_PARTY_LZ4CLI THIRD_PARTY_LZ4CLI_FILES := $(wildcard third_party/lz4cli/*) THIRD_PARTY_LZ4CLI_SRCS = $(filter %.c,$(THIRD_PARTY_LZ4CLI_FILES)) THIRD_PARTY_LZ4CLI_HDRS = $(filter %.h,$(THIRD_PARTY_LZ4CLI_FILES)) THIRD_PARTY_LZ4CLI = \ o/$(MODE)/third_party/lz4cli/lz4cli.com THIRD_PARTY_LZ4CLI_OBJS = \ o/$(MODE)/third_party/lz4cli/bench.o \ o/$(MODE)/third_party/lz4cli/lz4.o \ o/$(MODE)/third_party/lz4cli/lz4cli.o \ o/$(MODE)/third_party/lz4cli/lz4io.o \ o/$(MODE)/third_party/lz4cli/lz4hc.o \ o/$(MODE)/third_party/lz4cli/lz4frame.o \ o/$(MODE)/third_party/lz4cli/datagen.o \ o/$(MODE)/third_party/lz4cli/xxhash.o o/$(MODE)/third_party/lz4cli/lz4.o \ o/$(MODE)/third_party/lz4cli/lz4io.o \ o/$(MODE)/third_party/lz4cli/lz4hc.o \ o/$(MODE)/third_party/lz4cli/lz4frame.o \ o/$(MODE)/third_party/lz4cli/datagen.o: private \ DEFAULT_CPPFLAGS += \ -DSTACK_FRAME_UNLIMITED THIRD_PARTY_LZ4CLI_DIRECTDEPS = \ LIBC_INTRIN \ LIBC_STDIO \ LIBC_LOG \ LIBC_TIME THIRD_PARTY_LZ4CLI_DEPS := \ $(call uniq,$(foreach x,$(THIRD_PARTY_LZ4CLI_DIRECTDEPS),$($(x)))) $(THIRD_PARTY_LZ4CLI_OBJS): private \ DEFAULT_CPPFLAGS += \ -isystem third_party/lz4cli o/$(MODE)/third_party/lz4cli/lz4cli.com.dbg: \ $(THIRD_PARTY_LZ4CLI_DEPS) \ $(THIRD_PARTY_LZ4CLI_OBJS) \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/third_party/lz4cli/lz4cli.o: \ third_party/lz4cli/COPYING $(THIRD_PARTY_LZ4CLI_OBJS): \ $(BUILD_FILES) \ third_party/lz4cli/lz4cli.mk .PHONY: o/$(MODE)/third_party/lz4cli o/$(MODE)/third_party/lz4cli: $(THIRD_PARTY_LZ4CLI)
2,075
70
jart/cosmopolitan
false
cosmopolitan/third_party/lz4cli/lz4hc.c
/* clang-format off */ /* LZ4 HC - High Compression Mode of LZ4 Copyright (C) 2011-2017, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) 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. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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. You can contact the author at : - LZ4 source repository : https://github.com/lz4/lz4 - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c */ /* note : lz4hc is not an independent module, it requires lz4.h/lz4.c for proper compilation */ /* ************************************* * Tuning Parameter ***************************************/ /*! HEAPMODE : * Select how default compression function will allocate workplace memory, * in stack (0:fastest), or in heap (1:requires malloc()). * Since workplace is rather large, heap mode is recommended. */ #ifndef LZ4HC_HEAPMODE # define LZ4HC_HEAPMODE 1 #endif /*=== Dependency ===*/ #define LZ4_HC_STATIC_LINKING_ONLY #include "third_party/lz4cli/lz4hc.h" /*=== Common LZ4 definitions ===*/ #if defined(__GNUC__) # pragma GCC diagnostic ignored "-Wunused-function" #endif #if defined (__clang__) # pragma clang diagnostic ignored "-Wunused-function" #endif #define LZ4_COMMONDEFS_ONLY #include "third_party/lz4cli/lz4.c" /* LZ4_count, constants, mem */ /*=== Constants ===*/ #define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH) #define LZ4_OPT_NUM (1<<12) /*=== Macros ===*/ #ifndef MIN #define MIN(a,b) ( (a) < (b) ? (a) : (b) ) #define MAX(a,b) ( (a) > (b) ? (a) : (b) ) #endif #define HASH_FUNCTION(i) (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG)) #define DELTANEXTMAXD(p) chainTable[(p) & LZ4HC_MAXD_MASK] /* flexible, LZ4HC_MAXD dependent */ #define DELTANEXTU16(table, pos) table[(U16)(pos)] /* faster */ static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); } /*=== Enums ===*/ typedef enum { noDictCtx, usingDictCtx } dictCtx_directive; /************************************** * HC Compression **************************************/ static void LZ4HC_clearTables (LZ4HC_CCtx_internal* hc4) { MEM_INIT((void*)hc4->hashTable, 0, sizeof(hc4->hashTable)); MEM_INIT(hc4->chainTable, 0xFF, sizeof(hc4->chainTable)); } static void LZ4HC_init (LZ4HC_CCtx_internal* hc4, const BYTE* start) { uptrval startingOffset = hc4->end - hc4->base; if (startingOffset > 1 GB) { LZ4HC_clearTables(hc4); startingOffset = 0; } startingOffset += 64 KB; hc4->nextToUpdate = (U32) startingOffset; hc4->base = start - startingOffset; hc4->end = start; hc4->dictBase = start - startingOffset; hc4->dictLimit = (U32) startingOffset; hc4->lowLimit = (U32) startingOffset; } /* Update chains up to ip (excluded) */ LZ4_FORCE_INLINE void LZ4HC_Insert (LZ4HC_CCtx_internal* hc4, const BYTE* ip) { U16* const chainTable = hc4->chainTable; U32* const hashTable = hc4->hashTable; const BYTE* const base = hc4->base; U32 const target = (U32)(ip - base); U32 idx = hc4->nextToUpdate; while (idx < target) { U32 const h = LZ4HC_hashPtr(base+idx); size_t delta = idx - hashTable[h]; if (delta>MAX_DISTANCE) delta = MAX_DISTANCE; DELTANEXTU16(chainTable, idx) = (U16)delta; hashTable[h] = idx; idx++; } hc4->nextToUpdate = target; } /** LZ4HC_countBack() : * @return : negative value, nb of common bytes before ip/match */ LZ4_FORCE_INLINE int LZ4HC_countBack(const BYTE* const ip, const BYTE* const match, const BYTE* const iMin, const BYTE* const mMin) { int back = 0; int const min = (int)MAX(iMin - ip, mMin - match); assert(min <= 0); assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31)); assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31)); while ( (back > min) && (ip[back-1] == match[back-1]) ) back--; return back; } /* LZ4HC_countPattern() : * pattern32 must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!) */ static unsigned LZ4HC_countPattern(const BYTE* ip, const BYTE* const iEnd, U32 const pattern32) { const BYTE* const iStart = ip; reg_t const pattern = (sizeof(pattern)==8) ? (reg_t)pattern32 + (((reg_t)pattern32) << 32) : pattern32; while (likely(ip < iEnd-(sizeof(pattern)-1))) { reg_t const diff = LZ4_read_ARCH(ip) ^ pattern; if (!diff) { ip+=sizeof(pattern); continue; } ip += LZ4_NbCommonBytes(diff); return (unsigned)(ip - iStart); } if (LZ4_isLittleEndian()) { reg_t patternByte = pattern; while ((ip<iEnd) && (*ip == (BYTE)patternByte)) { ip++; patternByte >>= 8; } } else { /* big endian */ U32 bitOffset = (sizeof(pattern)*8) - 8; while (ip < iEnd) { BYTE const byte = (BYTE)(pattern >> bitOffset); if (*ip != byte) break; ip ++; bitOffset -= 8; } } return (unsigned)(ip - iStart); } /* LZ4HC_reverseCountPattern() : * pattern must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!) * read using natural platform endianess */ static unsigned LZ4HC_reverseCountPattern(const BYTE* ip, const BYTE* const iLow, U32 pattern) { const BYTE* const iStart = ip; while (likely(ip >= iLow+4)) { if (LZ4_read32(ip-4) != pattern) break; ip -= 4; } { const BYTE* bytePtr = (const BYTE*)(&pattern) + 3; /* works for any endianess */ while (likely(ip>iLow)) { if (ip[-1] != *bytePtr) break; ip--; bytePtr--; } } return (unsigned)(iStart - ip); } typedef enum { rep_untested, rep_not, rep_confirmed } repeat_state_e; typedef enum { favorCompressionRatio=0, favorDecompressionSpeed } HCfavor_e; LZ4_FORCE_INLINE int LZ4HC_InsertAndGetWiderMatch ( LZ4HC_CCtx_internal* hc4, const BYTE* const ip, const BYTE* const iLowLimit, const BYTE* const iHighLimit, int longest, const BYTE** matchpos, const BYTE** startpos, const int maxNbAttempts, const int patternAnalysis, const int chainSwap, const dictCtx_directive dict, const HCfavor_e favorDecSpeed) { U16* const chainTable = hc4->chainTable; U32* const HashTable = hc4->hashTable; const LZ4HC_CCtx_internal * const dictCtx = hc4->dictCtx; const BYTE* const base = hc4->base; const U32 dictLimit = hc4->dictLimit; const BYTE* const lowPrefixPtr = base + dictLimit; const U32 ipIndex = (U32)(ip - base); const U32 lowestMatchIndex = (hc4->lowLimit + 64 KB > ipIndex) ? hc4->lowLimit : ipIndex - MAX_DISTANCE; const BYTE* const dictBase = hc4->dictBase; int const lookBackLength = (int)(ip-iLowLimit); int nbAttempts = maxNbAttempts; int matchChainPos = 0; U32 const pattern = LZ4_read32(ip); U32 matchIndex; U32 dictMatchIndex; repeat_state_e repeat = rep_untested; size_t srcPatternLength = 0; DEBUGLOG(7, "LZ4HC_InsertAndGetWiderMatch"); /* First Match */ LZ4HC_Insert(hc4, ip); matchIndex = HashTable[LZ4HC_hashPtr(ip)]; DEBUGLOG(7, "First match at index %u / %u (lowestMatchIndex)", matchIndex, lowestMatchIndex); while ((matchIndex>=lowestMatchIndex) && (nbAttempts)) { int matchLength=0; nbAttempts--; assert(matchIndex < ipIndex); if (favorDecSpeed && (ipIndex - matchIndex < 8)) { /* do nothing */ } else if (matchIndex >= dictLimit) { /* within current Prefix */ const BYTE* const matchPtr = base + matchIndex; assert(matchPtr >= lowPrefixPtr); assert(matchPtr < ip); assert(longest >= 1); if (LZ4_read16(iLowLimit + longest - 1) == LZ4_read16(matchPtr - lookBackLength + longest - 1)) { if (LZ4_read32(matchPtr) == pattern) { int const back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, lowPrefixPtr) : 0; matchLength = MINMATCH + LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, iHighLimit); matchLength -= back; if (matchLength > longest) { longest = matchLength; *matchpos = matchPtr + back; *startpos = ip + back; } } } } else { /* lowestMatchIndex <= matchIndex < dictLimit */ const BYTE* const matchPtr = dictBase + matchIndex; if (LZ4_read32(matchPtr) == pattern) { const BYTE* const dictStart = dictBase + hc4->lowLimit; int back = 0; const BYTE* vLimit = ip + (dictLimit - matchIndex); if (vLimit > iHighLimit) vLimit = iHighLimit; matchLength = LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH; if ((ip+matchLength == vLimit) && (vLimit < iHighLimit)) matchLength += LZ4_count(ip+matchLength, lowPrefixPtr, iHighLimit); back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictStart) : 0; matchLength -= back; if (matchLength > longest) { longest = matchLength; *matchpos = base + matchIndex + back; /* virtual pos, relative to ip, to retrieve offset */ *startpos = ip + back; } } } if (chainSwap && matchLength==longest) { /* better match => select a better chain */ assert(lookBackLength==0); /* search forward only */ if (matchIndex + longest <= ipIndex) { U32 distanceToNextMatch = 1; int pos; for (pos = 0; pos <= longest - MINMATCH; pos++) { U32 const candidateDist = DELTANEXTU16(chainTable, matchIndex + pos); if (candidateDist > distanceToNextMatch) { distanceToNextMatch = candidateDist; matchChainPos = pos; } } if (distanceToNextMatch > 1) { if (distanceToNextMatch > matchIndex) break; /* avoid overflow */ matchIndex -= distanceToNextMatch; continue; } } } { U32 const distNextMatch = DELTANEXTU16(chainTable, matchIndex); if (patternAnalysis && distNextMatch==1 && matchChainPos==0) { U32 const matchCandidateIdx = matchIndex-1; /* may be a repeated pattern */ if (repeat == rep_untested) { if ( ((pattern & 0xFFFF) == (pattern >> 16)) & ((pattern & 0xFF) == (pattern >> 24)) ) { repeat = rep_confirmed; srcPatternLength = LZ4HC_countPattern(ip+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern); } else { repeat = rep_not; } } if ( (repeat == rep_confirmed) && (matchCandidateIdx >= dictLimit) ) { /* same segment only */ const BYTE* const matchPtr = base + matchCandidateIdx; if (LZ4_read32(matchPtr) == pattern) { /* good candidate */ size_t const forwardPatternLength = LZ4HC_countPattern(matchPtr+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern); const BYTE* const lowestMatchPtr = (lowPrefixPtr + MAX_DISTANCE >= ip) ? lowPrefixPtr : ip - MAX_DISTANCE; size_t const backLength = LZ4HC_reverseCountPattern(matchPtr, lowestMatchPtr, pattern); size_t const currentSegmentLength = backLength + forwardPatternLength; if ( (currentSegmentLength >= srcPatternLength) /* current pattern segment large enough to contain full srcPatternLength */ && (forwardPatternLength <= srcPatternLength) ) { /* haven't reached this position yet */ matchIndex = matchCandidateIdx + (U32)forwardPatternLength - (U32)srcPatternLength; /* best position, full pattern, might be followed by more match */ } else { matchIndex = matchCandidateIdx - (U32)backLength; /* farthest position in current segment, will find a match of length currentSegmentLength + maybe some back */ if (lookBackLength==0) { /* no back possible */ size_t const maxML = MIN(currentSegmentLength, srcPatternLength); if ((size_t)longest < maxML) { assert(base + matchIndex < ip); if (ip - (base+matchIndex) > MAX_DISTANCE) break; assert(maxML < 2 GB); longest = (int)maxML; *matchpos = base + matchIndex; /* virtual pos, relative to ip, to retrieve offset */ *startpos = ip; } { U32 const distToNextPattern = DELTANEXTU16(chainTable, matchIndex); if (distToNextPattern > matchIndex) break; /* avoid overflow */ matchIndex -= distToNextPattern; } } } continue; } } } } /* PA optimization */ /* follow current chain */ matchIndex -= DELTANEXTU16(chainTable, matchIndex+matchChainPos); } /* while ((matchIndex>=lowestMatchIndex) && (nbAttempts)) */ if (dict == usingDictCtx && nbAttempts && ipIndex - lowestMatchIndex < MAX_DISTANCE) { size_t const dictEndOffset = dictCtx->end - dictCtx->base; assert(dictEndOffset <= 1 GB); dictMatchIndex = dictCtx->hashTable[LZ4HC_hashPtr(ip)]; matchIndex = dictMatchIndex + lowestMatchIndex - (U32)dictEndOffset; while (ipIndex - matchIndex <= MAX_DISTANCE && nbAttempts--) { const BYTE* const matchPtr = dictCtx->base + dictMatchIndex; if (LZ4_read32(matchPtr) == pattern) { int mlt; int back = 0; const BYTE* vLimit = ip + (dictEndOffset - dictMatchIndex); if (vLimit > iHighLimit) vLimit = iHighLimit; mlt = LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH; back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictCtx->base + dictCtx->dictLimit) : 0; mlt -= back; if (mlt > longest) { longest = mlt; *matchpos = base + matchIndex + back; *startpos = ip + back; } } { U32 const nextOffset = DELTANEXTU16(dictCtx->chainTable, dictMatchIndex); dictMatchIndex -= nextOffset; matchIndex -= nextOffset; } } } return longest; } LZ4_FORCE_INLINE int LZ4HC_InsertAndFindBestMatch(LZ4HC_CCtx_internal* const hc4, /* Index table will be updated */ const BYTE* const ip, const BYTE* const iLimit, const BYTE** matchpos, const int maxNbAttempts, const int patternAnalysis, const dictCtx_directive dict) { const BYTE* uselessPtr = ip; /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos), * but this won't be the case here, as we define iLowLimit==ip, * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */ return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, matchpos, &uselessPtr, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio); } typedef enum { noLimit = 0, limitedOutput = 1, limitedDestSize = 2, } limitedOutput_directive; /* LZ4HC_encodeSequence() : * @return : 0 if ok, * 1 if buffer issue detected */ LZ4_FORCE_INLINE int LZ4HC_encodeSequence ( const BYTE** ip, BYTE** op, const BYTE** anchor, int matchLength, const BYTE* const match, limitedOutput_directive limit, BYTE* oend) { size_t length; BYTE* const token = (*op)++; #if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 6) static const BYTE* start = NULL; static U32 totalCost = 0; U32 const pos = (start==NULL) ? 0 : (U32)(*anchor - start); U32 const ll = (U32)(*ip - *anchor); U32 const llAdd = (ll>=15) ? ((ll-15) / 255) + 1 : 0; U32 const mlAdd = (matchLength>=19) ? ((matchLength-19) / 255) + 1 : 0; U32 const cost = 1 + llAdd + ll + 2 + mlAdd; if (start==NULL) start = *anchor; /* only works for single segment */ /* g_debuglog_enable = (pos >= 2228) & (pos <= 2262); */ DEBUGLOG(6, "pos:%7u -- literals:%3u, match:%4i, offset:%5u, cost:%3u + %u", pos, (U32)(*ip - *anchor), matchLength, (U32)(*ip-match), cost, totalCost); totalCost += cost; #endif /* Encode Literal length */ length = (size_t)(*ip - *anchor); if ((limit) && ((*op + (length >> 8) + length + (2 + 1 + LASTLITERALS)) > oend)) return 1; /* Check output limit */ if (length >= RUN_MASK) { size_t len = length - RUN_MASK; *token = (RUN_MASK << ML_BITS); for(; len >= 255 ; len -= 255) *(*op)++ = 255; *(*op)++ = (BYTE)len; } else { *token = (BYTE)(length << ML_BITS); } /* Copy Literals */ LZ4_wildCopy(*op, *anchor, (*op) + length); *op += length; /* Encode Offset */ assert( (*ip - match) <= MAX_DISTANCE ); /* note : consider providing offset as a value, rather than as a pointer difference */ LZ4_writeLE16(*op, (U16)(*ip-match)); *op += 2; /* Encode MatchLength */ assert(matchLength >= MINMATCH); length = (size_t)(matchLength - MINMATCH); if ((limit) && (*op + (length >> 8) + (1 + LASTLITERALS) > oend)) return 1; /* Check output limit */ if (length >= ML_MASK) { *token += ML_MASK; length -= ML_MASK; for(; length >= 510 ; length -= 510) { *(*op)++ = 255; *(*op)++ = 255; } if (length >= 255) { length -= 255; *(*op)++ = 255; } *(*op)++ = (BYTE)length; } else { *token += (BYTE)(length); } /* Prepare next loop */ *ip += matchLength; *anchor = *ip; return 0; } LZ4_FORCE_INLINE int LZ4HC_compress_hashChain ( LZ4HC_CCtx_internal* const ctx, const char* const source, char* const dest, int* srcSizePtr, int const maxOutputSize, unsigned maxNbAttempts, const limitedOutput_directive limit, const dictCtx_directive dict ) { const int inputSize = *srcSizePtr; const int patternAnalysis = (maxNbAttempts > 128); /* levels 9+ */ const BYTE* ip = (const BYTE*) source; const BYTE* anchor = ip; const BYTE* const iend = ip + inputSize; const BYTE* const mflimit = iend - MFLIMIT; const BYTE* const matchlimit = (iend - LASTLITERALS); BYTE* optr = (BYTE*) dest; BYTE* op = (BYTE*) dest; BYTE* oend = op + maxOutputSize; int ml0, ml, ml2, ml3; const BYTE* start0; const BYTE* ref0; const BYTE* ref = NULL; const BYTE* start2 = NULL; const BYTE* ref2 = NULL; const BYTE* start3 = NULL; const BYTE* ref3 = NULL; /* init */ *srcSizePtr = 0; if (limit == limitedDestSize) oend -= LASTLITERALS; /* Hack for support LZ4 format restriction */ if (inputSize < LZ4_minLength) goto _last_literals; /* Input too small, no compression (all literals) */ /* Main Loop */ while (ip <= mflimit) { ml = LZ4HC_InsertAndFindBestMatch (ctx, ip, matchlimit, &ref, maxNbAttempts, patternAnalysis, dict); if (ml<MINMATCH) { ip++; continue; } /* saved, in case we would skip too much */ start0 = ip; ref0 = ref; ml0 = ml; _Search2: if (ip+ml <= mflimit) { ml2 = LZ4HC_InsertAndGetWiderMatch(ctx, ip + ml - 2, ip + 0, matchlimit, ml, &ref2, &start2, maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio); } else { ml2 = ml; } if (ml2 == ml) { /* No better match => encode ML1 */ optr = op; if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow; continue; } if (start0 < ip) { /* first match was skipped at least once */ if (start2 < ip + ml0) { /* squeezing ML1 between ML0(original ML1) and ML2 */ ip = start0; ref = ref0; ml = ml0; /* restore initial ML1 */ } } /* Here, start0==ip */ if ((start2 - ip) < 3) { /* First Match too small : removed */ ml = ml2; ip = start2; ref =ref2; goto _Search2; } _Search3: /* At this stage, we have : * ml2 > ml1, and * ip1+3 <= ip2 (usually < ip1+ml1) */ if ((start2 - ip) < OPTIMAL_ML) { int correction; int new_ml = ml; if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML; if (ip+new_ml > start2 + ml2 - MINMATCH) new_ml = (int)(start2 - ip) + ml2 - MINMATCH; correction = new_ml - (int)(start2 - ip); if (correction > 0) { start2 += correction; ref2 += correction; ml2 -= correction; } } /* Now, we have start2 = ip+new_ml, with new_ml = min(ml, OPTIMAL_ML=18) */ if (start2 + ml2 <= mflimit) { ml3 = LZ4HC_InsertAndGetWiderMatch(ctx, start2 + ml2 - 3, start2, matchlimit, ml2, &ref3, &start3, maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio); } else { ml3 = ml2; } if (ml3 == ml2) { /* No better match => encode ML1 and ML2 */ /* ip & ref are known; Now for ml */ if (start2 < ip+ml) ml = (int)(start2 - ip); /* Now, encode 2 sequences */ optr = op; if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow; ip = start2; optr = op; if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml2, ref2, limit, oend)) goto _dest_overflow; continue; } if (start3 < ip+ml+3) { /* Not enough space for match 2 : remove it */ if (start3 >= (ip+ml)) { /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */ if (start2 < ip+ml) { int correction = (int)(ip+ml - start2); start2 += correction; ref2 += correction; ml2 -= correction; if (ml2 < MINMATCH) { start2 = start3; ref2 = ref3; ml2 = ml3; } } optr = op; if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow; ip = start3; ref = ref3; ml = ml3; start0 = start2; ref0 = ref2; ml0 = ml2; goto _Search2; } start2 = start3; ref2 = ref3; ml2 = ml3; goto _Search3; } /* * OK, now we have 3 ascending matches; * let's write the first one ML1. * ip & ref are known; Now decide ml. */ if (start2 < ip+ml) { if ((start2 - ip) < OPTIMAL_ML) { int correction; if (ml > OPTIMAL_ML) ml = OPTIMAL_ML; if (ip + ml > start2 + ml2 - MINMATCH) ml = (int)(start2 - ip) + ml2 - MINMATCH; correction = ml - (int)(start2 - ip); if (correction > 0) { start2 += correction; ref2 += correction; ml2 -= correction; } } else { ml = (int)(start2 - ip); } } optr = op; if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) goto _dest_overflow; /* ML2 becomes ML1 */ ip = start2; ref = ref2; ml = ml2; /* ML3 becomes ML2 */ start2 = start3; ref2 = ref3; ml2 = ml3; /* let's find a new ML3 */ goto _Search3; } _last_literals: /* Encode Last Literals */ { size_t lastRunSize = (size_t)(iend - anchor); /* literals */ size_t litLength = (lastRunSize + 255 - RUN_MASK) / 255; size_t const totalSize = 1 + litLength + lastRunSize; if (limit == limitedDestSize) oend += LASTLITERALS; /* restore correct value */ if (limit && (op + totalSize > oend)) { if (limit == limitedOutput) return 0; /* Check output limit */ /* adapt lastRunSize to fill 'dest' */ lastRunSize = (size_t)(oend - op) - 1; litLength = (lastRunSize + 255 - RUN_MASK) / 255; lastRunSize -= litLength; } ip = anchor + lastRunSize; if (lastRunSize >= RUN_MASK) { size_t accumulator = lastRunSize - RUN_MASK; *op++ = (RUN_MASK << ML_BITS); for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255; *op++ = (BYTE) accumulator; } else { *op++ = (BYTE)(lastRunSize << ML_BITS); } memcpy(op, anchor, lastRunSize); op += lastRunSize; } /* End */ *srcSizePtr = (int) (((const char*)ip) - source); return (int) (((char*)op)-dest); _dest_overflow: if (limit == limitedDestSize) { op = optr; /* restore correct out pointer */ goto _last_literals; } return 0; } static int LZ4HC_compress_optimal( LZ4HC_CCtx_internal* ctx, const char* const source, char* dst, int* srcSizePtr, int dstCapacity, int const nbSearches, size_t sufficient_len, const limitedOutput_directive limit, int const fullUpdate, const dictCtx_directive dict, HCfavor_e favorDecSpeed); LZ4_FORCE_INLINE int LZ4HC_compress_generic_internal ( LZ4HC_CCtx_internal* const ctx, const char* const src, char* const dst, int* const srcSizePtr, int const dstCapacity, int cLevel, const limitedOutput_directive limit, const dictCtx_directive dict ) { typedef enum { lz4hc, lz4opt } lz4hc_strat_e; typedef struct { lz4hc_strat_e strat; U32 nbSearches; U32 targetLength; } cParams_t; static const cParams_t clTable[LZ4HC_CLEVEL_MAX+1] = { { lz4hc, 2, 16 }, /* 0, unused */ { lz4hc, 2, 16 }, /* 1, unused */ { lz4hc, 2, 16 }, /* 2, unused */ { lz4hc, 4, 16 }, /* 3 */ { lz4hc, 8, 16 }, /* 4 */ { lz4hc, 16, 16 }, /* 5 */ { lz4hc, 32, 16 }, /* 6 */ { lz4hc, 64, 16 }, /* 7 */ { lz4hc, 128, 16 }, /* 8 */ { lz4hc, 256, 16 }, /* 9 */ { lz4opt, 96, 64 }, /*10==LZ4HC_CLEVEL_OPT_MIN*/ { lz4opt, 512,128 }, /*11 */ { lz4opt,16384,LZ4_OPT_NUM }, /* 12==LZ4HC_CLEVEL_MAX */ }; DEBUGLOG(4, "LZ4HC_compress_generic(%p, %p, %d)", ctx, src, *srcSizePtr); if (limit == limitedDestSize && dstCapacity < 1) return 0; /* Impossible to store anything */ if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size (too large or negative) */ ctx->end += *srcSizePtr; if (cLevel < 1) cLevel = LZ4HC_CLEVEL_DEFAULT; /* note : convention is different from lz4frame, maybe something to review */ cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel); { cParams_t const cParam = clTable[cLevel]; HCfavor_e const favor = ctx->favorDecSpeed ? favorDecompressionSpeed : favorCompressionRatio; if (cParam.strat == lz4hc) return LZ4HC_compress_hashChain(ctx, src, dst, srcSizePtr, dstCapacity, cParam.nbSearches, limit, dict); assert(cParam.strat == lz4opt); return LZ4HC_compress_optimal(ctx, src, dst, srcSizePtr, dstCapacity, cParam.nbSearches, cParam.targetLength, limit, cLevel == LZ4HC_CLEVEL_MAX, /* ultra mode */ dict, favor); } } static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock); static int LZ4HC_compress_generic_noDictCtx ( LZ4HC_CCtx_internal* const ctx, const char* const src, char* const dst, int* const srcSizePtr, int const dstCapacity, int cLevel, limitedOutput_directive limit ) { assert(ctx->dictCtx == NULL); return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, noDictCtx); } static int LZ4HC_compress_generic_dictCtx ( LZ4HC_CCtx_internal* const ctx, const char* const src, char* const dst, int* const srcSizePtr, int const dstCapacity, int cLevel, limitedOutput_directive limit ) { const size_t position = ctx->end - ctx->base - ctx->lowLimit; assert(ctx->dictCtx != NULL); if (position >= 64 KB) { ctx->dictCtx = NULL; return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit); } else if (position == 0 && *srcSizePtr > 4 KB) { memcpy(ctx, ctx->dictCtx, sizeof(LZ4HC_CCtx_internal)); LZ4HC_setExternalDict(ctx, (const BYTE *)src); ctx->compressionLevel = (short)cLevel; return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit); } else { return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, usingDictCtx); } } static int LZ4HC_compress_generic ( LZ4HC_CCtx_internal* const ctx, const char* const src, char* const dst, int* const srcSizePtr, int const dstCapacity, int cLevel, limitedOutput_directive limit ) { if (ctx->dictCtx == NULL) { return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit); } else { return LZ4HC_compress_generic_dictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit); } } int LZ4_sizeofStateHC(void) { return sizeof(LZ4_streamHC_t); } int LZ4_compress_HC_extStateHC_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel) { LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)state)->internal_donotuse; if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0; /* Error : state is not aligned for pointers (32 or 64 bits) */ LZ4_resetStreamHC_fast((LZ4_streamHC_t*)state, compressionLevel); LZ4HC_init (ctx, (const BYTE*)src); if (dstCapacity < LZ4_compressBound(srcSize)) return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, limitedOutput); else return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, noLimit); } int LZ4_compress_HC_extStateHC (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel) { if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0; /* Error : state is not aligned for pointers (32 or 64 bits) */ LZ4_resetStreamHC ((LZ4_streamHC_t*)state, compressionLevel); return LZ4_compress_HC_extStateHC_fastReset(state, src, dst, srcSize, dstCapacity, compressionLevel); } int LZ4_compress_HC(const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel) { #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1 LZ4_streamHC_t* const statePtr = (LZ4_streamHC_t*)ALLOC(sizeof(LZ4_streamHC_t)); #else LZ4_streamHC_t state; LZ4_streamHC_t* const statePtr = &state; #endif int const cSize = LZ4_compress_HC_extStateHC(statePtr, src, dst, srcSize, dstCapacity, compressionLevel); #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1 free(statePtr); #endif return cSize; } /* LZ4_compress_HC_destSize() : * only compatible with regular HC parser */ int LZ4_compress_HC_destSize(void* LZ4HC_Data, const char* source, char* dest, int* sourceSizePtr, int targetDestSize, int cLevel) { LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse; LZ4_resetStreamHC((LZ4_streamHC_t*)LZ4HC_Data, cLevel); LZ4HC_init(ctx, (const BYTE*) source); return LZ4HC_compress_generic(ctx, source, dest, sourceSizePtr, targetDestSize, cLevel, limitedDestSize); } /************************************** * Streaming Functions **************************************/ /* allocation */ LZ4_streamHC_t* LZ4_createStreamHC(void) { LZ4_streamHC_t* const LZ4_streamHCPtr = (LZ4_streamHC_t*)ALLOC(sizeof(LZ4_streamHC_t)); if (LZ4_streamHCPtr==NULL) return NULL; LZ4_resetStreamHC(LZ4_streamHCPtr, LZ4HC_CLEVEL_DEFAULT); return LZ4_streamHCPtr; } int LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr) { DEBUGLOG(4, "LZ4_freeStreamHC(%p)", LZ4_streamHCPtr); if (!LZ4_streamHCPtr) return 0; /* support free on NULL */ free(LZ4_streamHCPtr); return 0; } /* initialization */ void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel) { LZ4_STATIC_ASSERT(sizeof(LZ4HC_CCtx_internal) <= sizeof(size_t) * LZ4_STREAMHCSIZE_SIZET); /* if compilation fails here, LZ4_STREAMHCSIZE must be increased */ DEBUGLOG(4, "LZ4_resetStreamHC(%p, %d)", LZ4_streamHCPtr, compressionLevel); LZ4_streamHCPtr->internal_donotuse.end = (const BYTE *)(ptrdiff_t)-1; LZ4_streamHCPtr->internal_donotuse.base = NULL; LZ4_streamHCPtr->internal_donotuse.dictCtx = NULL; LZ4_streamHCPtr->internal_donotuse.favorDecSpeed = 0; LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel); } void LZ4_resetStreamHC_fast (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel) { DEBUGLOG(4, "LZ4_resetStreamHC_fast(%p, %d)", LZ4_streamHCPtr, compressionLevel); LZ4_streamHCPtr->internal_donotuse.end -= (uptrval)LZ4_streamHCPtr->internal_donotuse.base; LZ4_streamHCPtr->internal_donotuse.base = NULL; LZ4_streamHCPtr->internal_donotuse.dictCtx = NULL; LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel); } void LZ4_setCompressionLevel(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel) { if (compressionLevel < 1) compressionLevel = LZ4HC_CLEVEL_DEFAULT; if (compressionLevel > LZ4HC_CLEVEL_MAX) compressionLevel = LZ4HC_CLEVEL_MAX; LZ4_streamHCPtr->internal_donotuse.compressionLevel = (short)compressionLevel; } void LZ4_favorDecompressionSpeed(LZ4_streamHC_t* LZ4_streamHCPtr, int favor) { LZ4_streamHCPtr->internal_donotuse.favorDecSpeed = (favor!=0); } int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, const char* dictionary, int dictSize) { LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse; DEBUGLOG(4, "LZ4_loadDictHC(%p, %p, %d)", LZ4_streamHCPtr, dictionary, dictSize); if (dictSize > 64 KB) { dictionary += dictSize - 64 KB; dictSize = 64 KB; } LZ4_resetStreamHC(LZ4_streamHCPtr, ctxPtr->compressionLevel); LZ4HC_init (ctxPtr, (const BYTE*)dictionary); ctxPtr->end = (const BYTE*)dictionary + dictSize; if (dictSize >= 4) LZ4HC_Insert (ctxPtr, ctxPtr->end-3); return dictSize; } void LZ4_attach_HC_dictionary(LZ4_streamHC_t *working_stream, const LZ4_streamHC_t *dictionary_stream) { working_stream->internal_donotuse.dictCtx = dictionary_stream != NULL ? &(dictionary_stream->internal_donotuse) : NULL; } /* compression */ static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock) { DEBUGLOG(4, "LZ4HC_setExternalDict(%p, %p)", ctxPtr, newBlock); if (ctxPtr->end >= ctxPtr->base + ctxPtr->dictLimit + 4) LZ4HC_Insert (ctxPtr, ctxPtr->end-3); /* Referencing remaining dictionary content */ /* Only one memory segment for extDict, so any previous extDict is lost at this stage */ ctxPtr->lowLimit = ctxPtr->dictLimit; ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base); ctxPtr->dictBase = ctxPtr->base; ctxPtr->base = newBlock - ctxPtr->dictLimit; ctxPtr->end = newBlock; ctxPtr->nextToUpdate = ctxPtr->dictLimit; /* match referencing will resume from there */ } static int LZ4_compressHC_continue_generic (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int* srcSizePtr, int dstCapacity, limitedOutput_directive limit) { LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse; DEBUGLOG(4, "LZ4_compressHC_continue_generic(%p, %p, %d)", LZ4_streamHCPtr, src, *srcSizePtr); /* auto-init if forgotten */ if (ctxPtr->base == NULL) LZ4HC_init (ctxPtr, (const BYTE*) src); /* Check overflow */ if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB) { size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit; if (dictSize > 64 KB) dictSize = 64 KB; LZ4_loadDictHC(LZ4_streamHCPtr, (const char*)(ctxPtr->end) - dictSize, (int)dictSize); } /* Check if blocks follow each other */ if ((const BYTE*)src != ctxPtr->end) LZ4HC_setExternalDict(ctxPtr, (const BYTE*)src); /* Check overlapping input/dictionary space */ { const BYTE* sourceEnd = (const BYTE*) src + *srcSizePtr; const BYTE* const dictBegin = ctxPtr->dictBase + ctxPtr->lowLimit; const BYTE* const dictEnd = ctxPtr->dictBase + ctxPtr->dictLimit; if ((sourceEnd > dictBegin) && ((const BYTE*)src < dictEnd)) { if (sourceEnd > dictEnd) sourceEnd = dictEnd; ctxPtr->lowLimit = (U32)(sourceEnd - ctxPtr->dictBase); if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) ctxPtr->lowLimit = ctxPtr->dictLimit; } } return LZ4HC_compress_generic (ctxPtr, src, dst, srcSizePtr, dstCapacity, ctxPtr->compressionLevel, limit); } int LZ4_compress_HC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int srcSize, int dstCapacity) { if (dstCapacity < LZ4_compressBound(srcSize)) return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, limitedOutput); else return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, noLimit); } int LZ4_compress_HC_continue_destSize (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int* srcSizePtr, int targetDestSize) { return LZ4_compressHC_continue_generic(LZ4_streamHCPtr, src, dst, srcSizePtr, targetDestSize, limitedDestSize); } /* dictionary saving */ int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictSize) { LZ4HC_CCtx_internal* const streamPtr = &LZ4_streamHCPtr->internal_donotuse; int const prefixSize = (int)(streamPtr->end - (streamPtr->base + streamPtr->dictLimit)); DEBUGLOG(4, "LZ4_saveDictHC(%p, %p, %d)", LZ4_streamHCPtr, safeBuffer, dictSize); if (dictSize > 64 KB) dictSize = 64 KB; if (dictSize < 4) dictSize = 0; if (dictSize > prefixSize) dictSize = prefixSize; memmove(safeBuffer, streamPtr->end - dictSize, dictSize); { U32 const endIndex = (U32)(streamPtr->end - streamPtr->base); streamPtr->end = (const BYTE*)safeBuffer + dictSize; streamPtr->base = streamPtr->end - endIndex; streamPtr->dictLimit = endIndex - dictSize; streamPtr->lowLimit = endIndex - dictSize; if (streamPtr->nextToUpdate < streamPtr->dictLimit) streamPtr->nextToUpdate = streamPtr->dictLimit; } return dictSize; } /*********************************** * Deprecated Functions ***********************************/ /* These functions currently generate deprecation warnings */ /* Deprecated compression functions */ int LZ4_compressHC(const char* src, char* dst, int srcSize) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), 0); } int LZ4_compressHC_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, 0); } int LZ4_compressHC2(const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); } int LZ4_compressHC2_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, cLevel); } int LZ4_compressHC_withStateHC (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, LZ4_compressBound(srcSize), 0); } int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, maxDstSize, 0); } int LZ4_compressHC2_withStateHC (void* state, const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); } int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, maxDstSize, cLevel); } int LZ4_compressHC_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, LZ4_compressBound(srcSize)); } int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, maxDstSize); } /* Deprecated streaming functions */ int LZ4_sizeofStreamStateHC(void) { return LZ4_STREAMHCSIZE; } int LZ4_resetStreamStateHC(void* state, char* inputBuffer) { LZ4HC_CCtx_internal *ctx = &((LZ4_streamHC_t*)state)->internal_donotuse; if ((((size_t)state) & (sizeof(void*)-1)) != 0) return 1; /* Error : pointer is not aligned for pointer (32 or 64 bits) */ LZ4_resetStreamHC((LZ4_streamHC_t*)state, ((LZ4_streamHC_t*)state)->internal_donotuse.compressionLevel); LZ4HC_init(ctx, (const BYTE*)inputBuffer); return 0; } void* LZ4_createHC (const char* inputBuffer) { LZ4_streamHC_t* hc4 = (LZ4_streamHC_t*)ALLOC(sizeof(LZ4_streamHC_t)); if (hc4 == NULL) return NULL; /* not enough memory */ LZ4_resetStreamHC(hc4, 0 /* compressionLevel */); LZ4HC_init (&hc4->internal_donotuse, (const BYTE*)inputBuffer); return hc4; } int LZ4_freeHC (void* LZ4HC_Data) { if (!LZ4HC_Data) return 0; /* support free on NULL */ FREEMEM(LZ4HC_Data); return 0; } int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int cLevel) { return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, 0, cLevel, noLimit); } int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int dstCapacity, int cLevel) { return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, dstCapacity, cLevel, limitedOutput); } char* LZ4_slideInputBufferHC(void* LZ4HC_Data) { LZ4_streamHC_t *ctx = (LZ4_streamHC_t*)LZ4HC_Data; const BYTE *bufferStart = ctx->internal_donotuse.base + ctx->internal_donotuse.lowLimit; LZ4_resetStreamHC_fast(ctx, ctx->internal_donotuse.compressionLevel); /* avoid const char * -> char * conversion warning :( */ return (char *)(uptrval)bufferStart; } /* ================================================ * LZ4 Optimal parser (levels 10-12) * ===============================================*/ typedef struct { int price; int off; int mlen; int litlen; } LZ4HC_optimal_t; /* price in bytes */ LZ4_FORCE_INLINE int LZ4HC_literalsPrice(int const litlen) { int price = litlen; if (litlen >= (int)RUN_MASK) price += 1 + (litlen-RUN_MASK)/255; return price; } /* requires mlen >= MINMATCH */ LZ4_FORCE_INLINE int LZ4HC_sequencePrice(int litlen, int mlen) { int price = 1 + 2 ; /* token + 16-bit offset */ price += LZ4HC_literalsPrice(litlen); if (mlen >= (int)(ML_MASK+MINMATCH)) price += 1 + (mlen-(ML_MASK+MINMATCH))/255; return price; } typedef struct { int off; int len; } LZ4HC_match_t; LZ4_FORCE_INLINE LZ4HC_match_t LZ4HC_FindLongerMatch(LZ4HC_CCtx_internal* const ctx, const BYTE* ip, const BYTE* const iHighLimit, int minLen, int nbSearches, const dictCtx_directive dict, const HCfavor_e favorDecSpeed) { LZ4HC_match_t match = { 0 , 0 }; const BYTE* matchPtr = NULL; /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos), * but this won't be the case here, as we define iLowLimit==ip, * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */ int matchLength = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, minLen, &matchPtr, &ip, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed); if (matchLength <= minLen) return match; if (favorDecSpeed) { if ((matchLength>18) & (matchLength<=36)) matchLength=18; /* favor shortcut */ } match.len = matchLength; match.off = (int)(ip-matchPtr); return match; } static int LZ4HC_compress_optimal ( LZ4HC_CCtx_internal* ctx, const char* const source, char* dst, int* srcSizePtr, int dstCapacity, int const nbSearches, size_t sufficient_len, const limitedOutput_directive limit, int const fullUpdate, const dictCtx_directive dict, const HCfavor_e favorDecSpeed) { #define TRAILING_LITERALS 3 LZ4HC_optimal_t opt[LZ4_OPT_NUM + TRAILING_LITERALS]; /* ~64 KB, which is a bit large for stack... */ const BYTE* ip = (const BYTE*) source; const BYTE* anchor = ip; const BYTE* const iend = ip + *srcSizePtr; const BYTE* const mflimit = iend - MFLIMIT; const BYTE* const matchlimit = iend - LASTLITERALS; BYTE* op = (BYTE*) dst; BYTE* opSaved = (BYTE*) dst; BYTE* oend = op + dstCapacity; /* init */ DEBUGLOG(5, "LZ4HC_compress_optimal"); *srcSizePtr = 0; if (limit == limitedDestSize) oend -= LASTLITERALS; /* Hack for support LZ4 format restriction */ if (sufficient_len >= LZ4_OPT_NUM) sufficient_len = LZ4_OPT_NUM-1; /* Main Loop */ assert(ip - anchor < LZ4_MAX_INPUT_SIZE); while (ip <= mflimit) { int const llen = (int)(ip - anchor); int best_mlen, best_off; int cur, last_match_pos = 0; LZ4HC_match_t const firstMatch = LZ4HC_FindLongerMatch(ctx, ip, matchlimit, MINMATCH-1, nbSearches, dict, favorDecSpeed); if (firstMatch.len==0) { ip++; continue; } if ((size_t)firstMatch.len > sufficient_len) { /* good enough solution : immediate encoding */ int const firstML = firstMatch.len; const BYTE* const matchPos = ip - firstMatch.off; opSaved = op; if ( LZ4HC_encodeSequence(&ip, &op, &anchor, firstML, matchPos, limit, oend) ) /* updates ip, op and anchor */ goto _dest_overflow; continue; } /* set prices for first positions (literals) */ { int rPos; for (rPos = 0 ; rPos < MINMATCH ; rPos++) { int const cost = LZ4HC_literalsPrice(llen + rPos); opt[rPos].mlen = 1; opt[rPos].off = 0; opt[rPos].litlen = llen + rPos; opt[rPos].price = cost; DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i) -- initial setup", rPos, cost, opt[rPos].litlen); } } /* set prices using initial match */ { int mlen = MINMATCH; int const matchML = firstMatch.len; /* necessarily < sufficient_len < LZ4_OPT_NUM */ int const offset = firstMatch.off; assert(matchML < LZ4_OPT_NUM); for ( ; mlen <= matchML ; mlen++) { int const cost = LZ4HC_sequencePrice(llen, mlen); opt[mlen].mlen = mlen; opt[mlen].off = offset; opt[mlen].litlen = llen; opt[mlen].price = cost; DEBUGLOG(7, "rPos:%3i => price:%3i (matchlen=%i) -- initial setup", mlen, cost, mlen); } } last_match_pos = firstMatch.len; { int addLit; for (addLit = 1; addLit <= TRAILING_LITERALS; addLit ++) { opt[last_match_pos+addLit].mlen = 1; /* literal */ opt[last_match_pos+addLit].off = 0; opt[last_match_pos+addLit].litlen = addLit; opt[last_match_pos+addLit].price = opt[last_match_pos].price + LZ4HC_literalsPrice(addLit); DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i) -- initial setup", last_match_pos+addLit, opt[last_match_pos+addLit].price, addLit); } } /* check further positions */ for (cur = 1; cur < last_match_pos; cur++) { const BYTE* const curPtr = ip + cur; LZ4HC_match_t newMatch; if (curPtr > mflimit) break; DEBUGLOG(7, "rPos:%u[%u] vs [%u]%u", cur, opt[cur].price, opt[cur+1].price, cur+1); if (fullUpdate) { /* not useful to search here if next position has same (or lower) cost */ if ( (opt[cur+1].price <= opt[cur].price) /* in some cases, next position has same cost, but cost rises sharply after, so a small match would still be beneficial */ && (opt[cur+MINMATCH].price < opt[cur].price + 3/*min seq price*/) ) continue; } else { /* not useful to search here if next position has same (or lower) cost */ if (opt[cur+1].price <= opt[cur].price) continue; } DEBUGLOG(7, "search at rPos:%u", cur); if (fullUpdate) newMatch = LZ4HC_FindLongerMatch(ctx, curPtr, matchlimit, MINMATCH-1, nbSearches, dict, favorDecSpeed); else /* only test matches of minimum length; slightly faster, but misses a few bytes */ newMatch = LZ4HC_FindLongerMatch(ctx, curPtr, matchlimit, last_match_pos - cur, nbSearches, dict, favorDecSpeed); if (!newMatch.len) continue; if ( ((size_t)newMatch.len > sufficient_len) || (newMatch.len + cur >= LZ4_OPT_NUM) ) { /* immediate encoding */ best_mlen = newMatch.len; best_off = newMatch.off; last_match_pos = cur + 1; goto encode; } /* before match : set price with literals at beginning */ { int const baseLitlen = opt[cur].litlen; int litlen; for (litlen = 1; litlen < MINMATCH; litlen++) { int const price = opt[cur].price - LZ4HC_literalsPrice(baseLitlen) + LZ4HC_literalsPrice(baseLitlen+litlen); int const pos = cur + litlen; if (price < opt[pos].price) { opt[pos].mlen = 1; /* literal */ opt[pos].off = 0; opt[pos].litlen = baseLitlen+litlen; opt[pos].price = price; DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i)", pos, price, opt[pos].litlen); } } } /* set prices using match at position = cur */ { int const matchML = newMatch.len; int ml = MINMATCH; assert(cur + newMatch.len < LZ4_OPT_NUM); for ( ; ml <= matchML ; ml++) { int const pos = cur + ml; int const offset = newMatch.off; int price; int ll; DEBUGLOG(7, "testing price rPos %i (last_match_pos=%i)", pos, last_match_pos); if (opt[cur].mlen == 1) { ll = opt[cur].litlen; price = ((cur > ll) ? opt[cur - ll].price : 0) + LZ4HC_sequencePrice(ll, ml); } else { ll = 0; price = opt[cur].price + LZ4HC_sequencePrice(0, ml); } assert((U32)favorDecSpeed <= 1); if (pos > last_match_pos+TRAILING_LITERALS || price <= opt[pos].price - (int)favorDecSpeed) { DEBUGLOG(7, "rPos:%3i => price:%3i (matchlen=%i)", pos, price, ml); assert(pos < LZ4_OPT_NUM); if ( (ml == matchML) /* last pos of last match */ && (last_match_pos < pos) ) last_match_pos = pos; opt[pos].mlen = ml; opt[pos].off = offset; opt[pos].litlen = ll; opt[pos].price = price; } } } /* complete following positions with literals */ { int addLit; for (addLit = 1; addLit <= TRAILING_LITERALS; addLit ++) { opt[last_match_pos+addLit].mlen = 1; /* literal */ opt[last_match_pos+addLit].off = 0; opt[last_match_pos+addLit].litlen = addLit; opt[last_match_pos+addLit].price = opt[last_match_pos].price + LZ4HC_literalsPrice(addLit); DEBUGLOG(7, "rPos:%3i => price:%3i (litlen=%i)", last_match_pos+addLit, opt[last_match_pos+addLit].price, addLit); } } } /* for (cur = 1; cur <= last_match_pos; cur++) */ best_mlen = opt[last_match_pos].mlen; best_off = opt[last_match_pos].off; cur = last_match_pos - best_mlen; encode: /* cur, last_match_pos, best_mlen, best_off must be set */ assert(cur < LZ4_OPT_NUM); assert(last_match_pos >= 1); /* == 1 when only one candidate */ DEBUGLOG(6, "reverse traversal, looking for shortest path (last_match_pos=%i)", last_match_pos); { int candidate_pos = cur; int selected_matchLength = best_mlen; int selected_offset = best_off; while (1) { /* from end to beginning */ int const next_matchLength = opt[candidate_pos].mlen; /* can be 1, means literal */ int const next_offset = opt[candidate_pos].off; DEBUGLOG(7, "pos %i: sequence length %i", candidate_pos, selected_matchLength); opt[candidate_pos].mlen = selected_matchLength; opt[candidate_pos].off = selected_offset; selected_matchLength = next_matchLength; selected_offset = next_offset; if (next_matchLength > candidate_pos) break; /* last match elected, first match to encode */ assert(next_matchLength > 0); /* can be 1, means literal */ candidate_pos -= next_matchLength; } } /* encode all recorded sequences in order */ { int rPos = 0; /* relative position (to ip) */ while (rPos < last_match_pos) { int const ml = opt[rPos].mlen; int const offset = opt[rPos].off; if (ml == 1) { ip++; rPos++; continue; } /* literal; note: can end up with several literals, in which case, skip them */ rPos += ml; assert(ml >= MINMATCH); assert((offset >= 1) && (offset <= MAX_DISTANCE)); opSaved = op; if ( LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ip - offset, limit, oend) ) /* updates ip, op and anchor */ goto _dest_overflow; } } } /* while (ip <= mflimit) */ _last_literals: /* Encode Last Literals */ { size_t lastRunSize = (size_t)(iend - anchor); /* literals */ size_t litLength = (lastRunSize + 255 - RUN_MASK) / 255; size_t const totalSize = 1 + litLength + lastRunSize; if (limit == limitedDestSize) oend += LASTLITERALS; /* restore correct value */ if (limit && (op + totalSize > oend)) { if (limit == limitedOutput) return 0; /* Check output limit */ /* adapt lastRunSize to fill 'dst' */ lastRunSize = (size_t)(oend - op) - 1; litLength = (lastRunSize + 255 - RUN_MASK) / 255; lastRunSize -= litLength; } ip = anchor + lastRunSize; if (lastRunSize >= RUN_MASK) { size_t accumulator = lastRunSize - RUN_MASK; *op++ = (RUN_MASK << ML_BITS); for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255; *op++ = (BYTE) accumulator; } else { *op++ = (BYTE)(lastRunSize << ML_BITS); } memcpy(op, anchor, lastRunSize); op += lastRunSize; } /* End */ *srcSizePtr = (int) (((const char*)ip) - source); return (int) ((char*)op-dst); _dest_overflow: if (limit == limitedDestSize) { op = opSaved; /* restore correct out pointer */ goto _last_literals; } return 0; }
59,942
1,416
jart/cosmopolitan
false
cosmopolitan/third_party/python/repl.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/yoink.h" #include "third_party/python/runpythonmodule.h" #include "tool/args/args.h" // clang-format off int main(int argc, char **argv) { LoadZipArgs(&argc, &argv); return RunPythonModule(argc, argv); }
1,066
18
jart/cosmopolitan
false
cosmopolitan/third_party/python/LICENSE
A. HISTORY OF THE SOFTWARE ========================== Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands as a successor of a language called ABC. Guido remains Python's principal author, although it includes many contributions from others. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) in Reston, Virginia where he released several versions of the software. In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations, which became Zope Corporation. In 2001, the Python Software Foundation (PSF, see https://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation was a sponsoring member of the PSF. All Python releases are Open Source (see http://www.opensource.org for the Open Source Definition). Historically, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the various releases. Release Derived Year Owner GPL- from compatible? (1) 0.9.0 thru 1.2 1991-1995 CWI yes 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes 1.6 1.5.2 2000 CNRI no 2.0 1.6 2000 BeOpen.com no 1.6.1 1.6 2001 CNRI yes (2) 2.1 2.0+1.6.1 2001 PSF no 2.0.1 2.0+1.6.1 2001 PSF yes 2.1.1 2.1+2.0.1 2001 PSF yes 2.1.2 2.1.1 2002 PSF yes 2.1.3 2.1.2 2002 PSF yes 2.2 and above 2.1.1 2001-now PSF yes Footnotes: (1) GPL-compatible doesn't mean that we're distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don't. (2) According to Richard Stallman, 1.6.1 is not GPL-compatible, because its license has a choice of law clause. According to CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 is "not incompatible" with the GPL. Thanks to the many outside volunteers who have worked under Guido's direction to make these releases possible. B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON =============================================================== PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 -------------------------------------------- 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python. 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using Python, Licensee agrees to be bound by the terms and conditions of this License Agreement. BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 ------------------------------------------- BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization ("Licensee") accessing and otherwise using this software in source or binary form and its associated documentation ("the Software"). 2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee. 3. BeOpen is making the Software available to Licensee on an "AS IS" basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 5. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any third party. As an exception, the "BeOpen Python" logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page. 7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement. CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 --------------------------------------- 1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 ("CNRI"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided, however, that CNRI's License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) 1995-2001 Corporation for National Research Initiatives; All Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI's License Agreement, Licensee may substitute the following text (omitting the quotes): "Python 1.6.1 is made available subject to the terms and conditions in CNRI's License Agreement. This Agreement together with Python 1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following URL: http://hdl.handle.net/1895.22/1013". 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 1.6.1. 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia's conflict of law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non-separable material that was previously distributed under the GNU General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By clicking on the "ACCEPT" button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement. ACCEPT CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 -------------------------------------------------- Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
12,781
255
jart/cosmopolitan
false
cosmopolitan/third_party/python/runpythonmodule.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "libc/calls/calls.h" #include "libc/calls/internal.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/struct/sigset.h" #include "libc/calls/ucontext.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/bits.h" #include "libc/intrin/safemacros.internal.h" #include "libc/intrin/weaken.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/runtime/symbols.internal.h" #include "libc/stdio/stdio.h" #include "libc/str/locale.h" #include "libc/str/str.h" #include "libc/sysv/consts/fileno.h" #include "libc/sysv/consts/prot.h" #include "libc/sysv/consts/sig.h" #include "libc/time/time.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #include "third_party/linenoise/linenoise.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/funcobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/moduleobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pyport.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/yoink.h" #include "third_party/xed/x86.h" // clang-format off STATIC_STACK_SIZE(0x100000); STATIC_YOINK("__die"); STATIC_YOINK("zip_uri_support"); PYTHON_YOINK("cosmo"); PYTHON_YOINK("_locale"); PYTHON_YOINK("_bootlocale"); PYTHON_YOINK("encodings.aliases"); PYTHON_YOINK("encodings.latin_1"); PYTHON_YOINK("encodings.utf_8"); extern char kLaunchPythonModuleName[]; /* optionally generated by pyobj.com */ const struct _frozen *PyImport_FrozenModules = _PyImport_FrozenModules; struct _inittab *PyImport_Inittab = _PyImport_Inittab; static int g_gotint; static void OnKeyboardInterrupt(int sig) { g_gotint = sig; } static void AddCompletion(linenoiseCompletions *c, char *s) { char **p = c->cvec; size_t n = c->len + 1; if ((p = realloc(p, n * sizeof(*p)))) { p[n - 1] = s; c->cvec = p; c->len = n; } } static void CompleteModule(const char *s, const char *p, linenoiseCompletions *c) { const char *name; struct _inittab *it; Py_ssize_t plen, namelen; PyObject *m, *f, *g, *i, *v, *n; plen = strlen(p); for (it = PyImport_Inittab; it->name; ++it) { if (_startswithi(it->name, p)) { AddCompletion(c, xasprintf("%s%s", s, it->name + plen)); } } if ((m = PyImport_ImportModule("pkgutil"))) { if ((f = PyObject_GetAttrString(m, "iter_modules"))) { if ((g = PyObject_CallFunctionObjArgs(f, 0))) { if ((i = PyObject_GetIter(g))) { while ((v = PyIter_Next(i))) { if ((n = PyObject_GetAttrString(v, "name"))) { if (((name = PyUnicode_AsUTF8AndSize(n, &namelen)) && namelen >= plen && !memcasecmp(name, p, plen))) { AddCompletion(c, xasprintf("%s%s", s, name + plen)); } Py_DECREF(n); } Py_DECREF(v); } Py_DECREF(i); } Py_DECREF(g); } Py_DECREF(f); } Py_DECREF(m); } } static void CompleteDict(const char *b, const char *q, const char *p, linenoiseCompletions *c, PyObject *o) { const char *s; PyObject *k, *v; Py_ssize_t i, m; for (i = 0; PyDict_Next(o, &i, &k, &v);) { if ((v != Py_None && PyUnicode_Check(k) && (s = PyUnicode_AsUTF8AndSize(k, &m)) && m >= q - p && !memcasecmp(s, p, q - p))) { AddCompletion(c, xasprintf("%.*s%.*s", p - b, b, m, s)); } } } static void CompleteDir(const char *b, const char *q, const char *p, linenoiseCompletions *c, PyObject *o) { Py_ssize_t m; const char *s; PyObject *d, *i, *k; if ((d = PyObject_Dir(o))) { if ((i = PyObject_GetIter(d))) { while ((k = PyIter_Next(i))) { if (((s = PyUnicode_AsUTF8AndSize(k, &m)) && m >= q - p && !memcasecmp(s, p, q - p) && !(q - p == 0 && m > 4 && (s[0+0] == '_' && s[0+1] == '_' && s[m-1] == '_' && s[m-2] == '_')))) { AddCompletion(c, xasprintf("%.*s%.*s", p - b, b, m, s)); } Py_DECREF(k); } Py_DECREF(i); } Py_DECREF(d); } } static void Complete(const char *p, linenoiseCompletions *c) { PyObject *o, *t, *i; const char *q, *s, *b; if (_startswith(p, "import ")) { for (q = p + 7; *q; ++q) { if (!isalnum(*q) && *q != '_') { return; } } CompleteModule(p, p + 7, c); return; } for (b = p, p += strlen(p); p > b; --p) { if (!isalnum(p[-1]) && p[-1] != '.' && p[-1] != '_') { break; } } o = PyModule_GetDict(PyImport_AddModule("__main__")); if (!*(q = strchrnul(p, '.'))) { CompleteDict(b, q, p, c, o); CompleteDir(b, q, p, c, PyDict_GetItemString(o, "__builtins__")); } else { s = strndup(p, q - p); if ((t = PyDict_GetItemString(o, s))) { Py_INCREF(t); } else { o = PyDict_GetItemString(o, "__builtins__"); if (PyObject_HasAttrString(o, s)) { t = PyObject_GetAttrString(o, s); } } while ((p = q + 1), (o = t)) { if (*(q = strchrnul(p, '.'))) { t = PyObject_GetAttrString(o, gc(strndup(p, q - p))); Py_DECREF(o); } else { CompleteDir(b, q, p, c, o); Py_DECREF(o); break; } } free(s); } } static void TerminalCompletion(const char *p, linenoiseCompletions *c) { // Complete(p, c); if (PyErr_Occurred()) { PyErr_Clear(); } } static char * TerminalHint(const char *p, const char **ansi1, const char **ansi2) { char *h = 0; linenoiseCompletions c = {0}; TerminalCompletion(p, &c); if (c.len == 1) h = strdup(c.cvec[0] + strlen(p)); linenoiseFreeCompletions(&c); return h; } static char * ReinterpretCommand(const char *line) { size_t n; n = strlen(line); if (n && line[n - 1] == '?') { return xstrcat("help(", gc(strndup(gc(line), n - 1)), ')'); } else { return line; } } static char * TerminalReadline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt) { size_t n; char *p, *q; PyOS_sighandler_t saint; saint = PyOS_setsig(SIGINT, OnKeyboardInterrupt); p = linenoiseWithHistory(prompt, "python"); PyOS_setsig(SIGINT, saint); if (g_gotint) { PyOS_setsig(SIGINT, saint); g_gotint = 0; q = 0; } else if (p) { p = ReinterpretCommand(p); n = strlen(p); q = PyMem_RawMalloc(n + 2); strcpy(mempcpy(q, p, n), "\n"); clearerr(sys_stdin); } else if ((q = PyMem_RawMalloc(1))) { *q = 0; } free(p); return q; } int RunPythonModule(int argc, char **argv) { char *launchargs[4]; wchar_t **argv_copy; /* We need a second copy, as Python might modify the first one. */ wchar_t **argv_copy2; int i, res; char *oldloc; if (argc == 1 && _weaken(kLaunchPythonModuleName)) { launchargs[0] = argv[0]; launchargs[1] = strdup("-m"); launchargs[2] = strdup(kLaunchPythonModuleName); launchargs[3] = 0; argc = 3; argv = launchargs; } PyOS_ReadlineFunctionPointer = TerminalReadline; linenoiseSetCompletionCallback(TerminalCompletion); linenoiseSetHintsCallback(TerminalHint); linenoiseSetFreeHintsCallback(free); #if IsModeDbg() /* Force malloc() allocator to bootstrap Python */ _PyMem_SetupAllocators("malloc"); #endif argv_copy = (wchar_t **)PyMem_RawMalloc(sizeof(wchar_t*) * (argc+1)); argv_copy2 = (wchar_t **)PyMem_RawMalloc(sizeof(wchar_t*) * (argc+1)); if (!argv_copy || !argv_copy2) { fprintf(stderr, "out of memory\n"); return 1; } /* 754 requires that FP exceptions run in "no stop" mode by default, * and until C vendors implement C99's ways to control FP exceptions, * Python requires non-stop mode. Alas, some platforms enable FP * exceptions by default. Here we disable them. */ #ifdef __FreeBSD__ fedisableexcept(FE_OVERFLOW); #endif oldloc = _PyMem_RawStrdup(setlocale(LC_ALL, NULL)); if (!oldloc) { fprintf(stderr, "out of memory\n"); return 1; } setlocale(LC_ALL, ""); for (i = 0; i < argc; i++) { argv_copy[i] = Py_DecodeLocale(argv[i], NULL); if (!argv_copy[i]) { PyMem_RawFree(oldloc); fprintf(stderr, "Fatal Python error: " "unable to decode the command line argument #%i\n", i + 1); return 1; } argv_copy2[i] = argv_copy[i]; } argv_copy2[argc] = argv_copy[argc] = NULL; setlocale(LC_ALL, oldloc); PyMem_RawFree(oldloc); res = Py_Main(argc, argv_copy); #if IsModeDbg() /* Force again malloc() allocator to release memory blocks allocated before Py_Main() */ _PyMem_SetupAllocators("malloc"); #endif for (i = 0; i < argc; i++) { PyMem_RawFree(argv_copy2[i]); } PyMem_RawFree(argv_copy); PyMem_RawFree(argv_copy2); return res; }
11,071
356
jart/cosmopolitan
false
cosmopolitan/third_party/python/pydump.py
# read a .pyc file and pretty-print it # copied from https://gist.github.com/twerp/fdc9975f0461821fcd3d7679d1f0f7e9 # copied from http://nedbatchelder.com/blog/200804/the_structure_of_pyc_files.html # and updated to Python 3.5 (Nov 10th 2015) import dis, marshal, struct, sys, time, types, binascii def show_file(fname): f = open(fname, "rb") magic = f.read(4) moddate = f.read(4) filesz = f.read(4) modtime = time.asctime(time.localtime(struct.unpack('=L', moddate)[0])) filesz = struct.unpack('=L', filesz) print("magic %s" % (binascii.hexlify(magic))) print("moddate %s (%s)" % (binascii.hexlify(moddate), modtime)) print("files sz %d" % filesz) code = marshal.load(f) show_code(code) def show_code(code, indent=''): print("%scode" % indent) indent += ' ' print("%sargcount %d" % (indent, code.co_argcount)) print("%snlocals %d" % (indent, code.co_nlocals)) print("%sstacksize %d" % (indent, code.co_stacksize)) print("%sflags %04x" % (indent, code.co_flags)) show_hex("code", code.co_code, indent=indent) dis.disassemble(code) print("%sconsts" % indent) for const in code.co_consts: if type(const) == types.CodeType: show_code(const, indent+' ') else: print(" %s%r" % (indent, const)) print("%snames %r" % (indent, code.co_names)) print("%svarnames %r" % (indent, code.co_varnames)) print("%sfreevars %r" % (indent, code.co_freevars)) print("%scellvars %r" % (indent, code.co_cellvars)) print("%sfilename %r" % (indent, code.co_filename)) print("%sname %r" % (indent, code.co_name)) print("%sfirstlineno %d" % (indent, code.co_firstlineno)) show_hex("lnotab", code.co_lnotab, indent=indent) def show_hex(label, h, indent): h = binascii.hexlify(h) if len(h) < 60: print("%s%s %s" % (indent, label, h)) else: print("%s%s" % (indent, label)) for i in range(0, len(h), 60): print("%s %s" % (indent, h[i:i+60])) show_file(sys.argv[1])
2,051
55
jart/cosmopolitan
false
cosmopolitan/third_party/python/pycomp.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/stat.h" #include "libc/fmt/conv.h" #include "libc/intrin/bits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/mem/gc.h" #include "libc/runtime/runtime.h" #include "libc/sysv/consts/o.h" #include "libc/x/x.h" #include "libc/x/xasprintf.h" #include "third_party/getopt/getopt.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/compile.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/marshal.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/ucnhash.h" #include "third_party/python/Include/yoink.h" #include "tool/build/lib/stripcomponents.h" /* clang-format off */ STATIC_YOINK("_PyUnicode_GetCode"); #define MANUAL "\ SYNOPSIS\n\ \n\ pycomp.com [FLAGS] SOURCE\n\ \n\ OVERVIEW\n\ \n\ Python Compiler\n\ \n\ FLAGS\n\ \n\ -o PATH specified output pyc file\n\ -O0 don't optimize [default]\n\ -O1 remove debug statements\n\ -O2 remove debug statements and docstrings\n\ -n do nothing\n\ -h help\n\ \n\ EXAMPLE\n\ \n\ pycomp.com -o foo/__pycache__/__init__.cpython-3.6.pyc foo/__init__.py\n\ \n" int optimize; char *inpath; char *outpath; void GetOpts(int argc, char *argv[]) { int opt; char *outdir; while ((opt = getopt(argc, argv, "hnO:o:")) != -1) { switch (opt) { case 'O': optimize = atoi(optarg); break; case 'o': outpath = optarg; break; case 'n': exit(0); case 'h': fputs(MANUAL, stdout); exit(0); default: fputs(MANUAL, stderr); exit(1); } } if (argc - optind != 1) { fputs("error: need one input file\n", stderr); exit(1); } inpath = argv[optind]; if (!outpath) { outpath = xasprintf("%sc", inpath); } } int main(int argc, char *argv[]) { int fd; char *name; ssize_t rc; size_t i, n; struct stat st; char *s, *p, m[12]; PyObject *code, *marshalled; ShowCrashReports(); GetOpts(argc, argv); marshalled = 0; if (stat(inpath, &st) == -1) perror(inpath), exit(1); CHECK_NOTNULL((p = _gc(xslurp(inpath, &n)))); Py_NoUserSiteDirectory++; Py_NoSiteFlag++; Py_IgnoreEnvironmentFlag++; Py_FrozenFlag++; /* Py_VerboseFlag++; */ Py_SetProgramName(_gc(utf8to32(argv[0], -1, 0))); _Py_InitializeEx_Private(1, 0); name = _gc(xjoinpaths("/zip/.python", StripComponents(inpath, 3))); code = Py_CompileStringExFlags(p, name, Py_file_input, NULL, optimize); if (!code) goto error; marshalled = PyMarshal_WriteObjectToString(code, Py_MARSHAL_VERSION); Py_CLEAR(code); if (!marshalled) goto error; assert(PyBytes_CheckExact(marshalled)); p = PyBytes_AS_STRING(marshalled); n = PyBytes_GET_SIZE(marshalled); CHECK_NE(-1, (fd = open(outpath, O_CREAT|O_TRUNC|O_WRONLY, 0644))); WRITE16LE(m+0, 3390); /* Python 3.7a1 */ WRITE16LE(m+2, READ16LE("\r\n")); WRITE32LE(m+4, st.st_mtim.tv_sec); /* tsk tsk y2038 */ WRITE32LE(m+8, n); CHECK_EQ(sizeof(m), write(fd, m, sizeof(m))); for (i = 0; i < n; i += rc) { CHECK_NE(-1, (rc = write(fd, p + i, n - i))); } CHECK_NE(-1, close(fd)); Py_CLEAR(marshalled); Py_Finalize(); return 0; error: PyErr_Print(); Py_Finalize(); if (marshalled) Py_DECREF(marshalled); return 1; }
5,673
159
jart/cosmopolitan
false
cosmopolitan/third_party/python/freeze.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/log/log.h" #include "libc/mem/mem.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/compile.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/marshal.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pythonrun.h" /* clang-format off */ #define HEADER "\ /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│\n\ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│\n\ ╞══════════════════════════════════════════════════════════════════════════════╡\n\ │ Python 3 │\n\ │ https://docs.python.org/3/license.html │\n\ ╚─────────────────────────────────────────────────────────────────────────────*/\n\ /* clang-format off */\n\ \n\ /*\n\ * Auto-generated by\n\ * o/third_party/python/freeze \\\n\ * %s \\\n\ * %s\n\ */\n\ \n\ " int main(int argc, char *argv[]) { char *inpath, *outpath, *code_name; FILE *infile = NULL, *outfile = NULL; struct _Py_stat_struct status; size_t text_size, data_size, n; char *text = NULL; unsigned char *data; PyObject *code = NULL, *marshalled = NULL; int is_bootstrap = 1; if (argc == 2 && !strcmp(argv[1], "-n")) return 0; if (argc != 3) { fprintf(stderr, "need to specify input and output paths\n"); return 2; } inpath = argv[1]; outpath = argv[2]; infile = fopen(inpath, "rb"); if (infile == NULL) { fprintf(stderr, "cannot open '%s' for reading\n", inpath); goto error; } if (_Py_fstat_noraise(fileno(infile), &status)) { fprintf(stderr, "cannot fstat '%s'\n", inpath); goto error; } text_size = (size_t)status.st_size; text = (char *) malloc(text_size + 1); if (text == NULL) { fprintf(stderr, "could not allocate %ld bytes\n", (long) text_size); goto error; } n = fread(text, 1, text_size, infile); fclose(infile); infile = NULL; if (n < text_size) { fprintf(stderr, "read too short: got %ld instead of %ld bytes\n", (long) n, (long) text_size); goto error; } text[text_size] = '\0'; Py_NoUserSiteDirectory++; Py_NoSiteFlag++; Py_IgnoreEnvironmentFlag++; Py_FrozenFlag++; Py_SetProgramName(L"./_freeze_importlib"); /* Don't install importlib, since it could execute outdated bytecode. */ _Py_InitializeEx_Private(1, 0); if (strstr(inpath, "_external") != NULL) { is_bootstrap = 0; } code_name = is_bootstrap ? "<frozen importlib._bootstrap>" : "<frozen importlib._bootstrap_external>"; code = Py_CompileStringExFlags(text, code_name, Py_file_input, NULL, 2); if (code == NULL) goto error; free(text); text = NULL; marshalled = PyMarshal_WriteObjectToString(code, Py_MARSHAL_VERSION); Py_CLEAR(code); if (marshalled == NULL) goto error; assert(PyBytes_CheckExact(marshalled)); data = (unsigned char *) PyBytes_AS_STRING(marshalled); data_size = PyBytes_GET_SIZE(marshalled); /* Open the file in text mode. The hg checkout should be using the eol extension, which in turn should cause the EOL style match the C library's text mode */ outfile = fopen(outpath, "w"); if (outfile == NULL) { fprintf(stderr, "cannot open '%s' for writing\n", outpath); goto error; } fprintf(outfile, HEADER, argv[1], argv[2]); if (is_bootstrap) fprintf(outfile, "const unsigned char _Py_M__importlib[] = {\n"); else fprintf(outfile, "const unsigned char _Py_M__importlib_external[] = {\n"); for (n = 0; n < data_size; n += 16) { size_t i, end = Py_MIN(n + 16, data_size); fprintf(outfile, " "); for (i = n; i < end; i++) { fprintf(outfile, "%d,", (unsigned int) data[i]); } fprintf(outfile, "\n"); } fprintf(outfile, "};\n"); Py_CLEAR(marshalled); Py_Finalize(); if (outfile) { if (ferror(outfile)) { fprintf(stderr, "error when writing to '%s'\n", outpath); goto error; } fclose(outfile); } return 0; error: PyErr_Print(); Py_Finalize(); if (infile) fclose(infile); if (outfile) fclose(outfile); if (text) free(text); if (marshalled) Py_DECREF(marshalled); return 1; }
5,923
163
jart/cosmopolitan
false
cosmopolitan/third_party/python/README.cosmo
ORIGIN Python 3.6.14 https://github.com/python/cpython/tree/3.6 0a0a135bae2692d069b18d2d590397fbe0a0d39a LICENSE Python License https://docs.python.org/3/license.html LOCAL CHANGES - Restore octal notation - Support \e → 033 escapes - Undiamond #include lines - Support zipos file loading - Make Python binaries work on six operating systems - Have Python REPL copyright() show dependent notices too
451
20
jart/cosmopolitan
false
cosmopolitan/third_party/python/pyobj.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/struct/iovec.h" #include "libc/calls/struct/stat.h" #include "libc/elf/def.h" #include "libc/fmt/conv.h" #include "libc/intrin/bits.h" #include "libc/log/check.h" #include "libc/log/log.h" #include "libc/macros.internal.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/stdio/append.h" #include "libc/stdio/stdio.h" #include "libc/sysv/consts/clock.h" #include "libc/sysv/consts/o.h" #include "libc/time/time.h" #include "libc/x/x.h" #include "libc/zip.h" #include "third_party/getopt/getopt.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/compile.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/marshal.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/opcode.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/unicodeobject.h" #include "tool/build/lib/elfwriter.h" #include "tool/build/lib/interner.h" #include "tool/build/lib/stripcomponents.h" /* clang-format off */ STATIC_YOINK("_PyUnicode_GetCode"); #define MANUAL "\ SYNOPSIS\n\ \n\ pyobj.com [FLAGS] SOURCE\n\ \n\ OVERVIEW\n\ \n\ Python Objectifier\n\ \n\ FLAGS\n\ \n\ -o PATH output elf object file\n\ -P STR prefix fake zip directory (default .python)\n\ -C INT strip directory components from src in zip\n\ -Y SYM append yoink to elf object [repeatable]\n\ -O0 don't optimize [default]\n\ -O1 remove debug statements\n\ -O2 remove debug statements and docstrings\n\ -B binary only (don't include .py file)\n\ -m insert executable launch.c main\n\ -r insert executable repl.c main\n\ -t insert unit test framework\n\ -0 zip uncompressed\n\ -n do nothing\n\ -h help\n\ \n" const char *const kIgnoredModules[] = /* sorted */ { "__main__", /* todo? */ "_dummy_threading", /* evil code */ "_dummy_threading.Thread", "_dummy_threading.__all__", "_overlapped", /* don't recognize if sys.platform yet */ "_scproxy", /* don't recognize if sys.platform yet */ "_winapi", /* don't recognize if sys.platform yet */ "asyncio.test_support", /* todo??? */ "builtins", "concurrent.futures", /* asyncio's fault */ "concurrent.futures._base", "concurrent.futures.process", "distutils.command.bdist", "distutils.command.bdist_dumb", "distutils.command.bdist_rpm", "distutils.command.bdist_wininst", "distutils.command.build", "distutils.command.build_clib", "distutils.command.build_ext", "distutils.command.build_py", "distutils.command.build_scripts", "distutils.command.check", "distutils.command.clean", "distutils.command.install", "distutils.command.install_data", "distutils.command.install_headers", "distutils.command.install_lib", "distutils.command.install_scripts", "distutils.command.register", "distutils.command.sdist", "distutils.command.upload", "distutils.spawn._nt_quote_args", "encodings.aliases", "importlib._bootstrap", "importlib._bootstrap.BuiltinImporter", "importlib._bootstrap.FrozenImporter", "importlib._bootstrap.ModuleSpec", "importlib._bootstrap._ERR_MSG", "importlib._bootstrap.__import__", "importlib._bootstrap._builtin_from_name", "importlib._bootstrap._exec", "importlib._bootstrap._find_spec", "importlib._bootstrap._load", "importlib._bootstrap._resolve_name", "importlib._bootstrap.module_from_spec", "importlib._bootstrap.spec_from_loader", "importlib._bootstrap_external", "importlib._bootstrap_external.BYTECODE_SUFFIXES", "importlib._bootstrap_external.DEBUG_BYTECODE_SUFFIXES", "importlib._bootstrap_external.EXTENSION_SUFFIXES", "importlib._bootstrap_external.ExtensionFileLoader", "importlib._bootstrap_external.FileFinder", "importlib._bootstrap_external.MAGIC_NUMBER", "importlib._bootstrap_external.OPTIMIZED_BYTECODE_SUFFIXES", "importlib._bootstrap_external.PathFinder", "importlib._bootstrap_external.SOURCE_SUFFIXES", "importlib._bootstrap_external.SourceFileLoader", "importlib._bootstrap_external.SourcelessFileLoader", "importlib._bootstrap_external.WindowsRegistryFinder", "importlib._bootstrap_external.cache_from_source", "importlib._bootstrap_external.decode_source", "importlib._bootstrap_external.source_from_cache", "importlib._bootstrap_external.spec_from_file_location", "java", /* don't recognize if sys.platform yet */ "java.lang", /* don't recognize if sys.platform yet */ "msvcrt", /* don't recognize if sys.platform yet */ "msvcrt.setmode", /* don't recognize if sys.platform yet */ "nt", /* os module don't care */ "nt._getfinalpathname", "os.path", "os.path._get_sep", "os.path._joinrealpath", "os.path._varprog", "os.path._varprogb", "os.path.abspath", "os.path.altsep", "os.path.basename", "os.path.commonpath", "os.path.commonprefix", "os.path.curdir", "os.path.defpath", "os.path.devnull", "os.path.dirname", "os.path.exists", "os.path.expanduser", "os.path.expandvars", "os.path.extsep", "os.path.genericpath", "os.path.getatime", "os.path.getctime", "os.path.getmtime", "os.path.getsize", "os.path.isabs", "os.path.isdir", "os.path.isfile", "os.path.islink", "os.path.ismount", "os.path.join", "os.path.lexists", "os.path.normcase", "os.path.normpath", "os.path.os", "os.path.pardir", "os.path.pathsep", "os.path.realpath", "os.path.relpath", "os.path.samefile", "os.path.sameopenfile", "os.path.samestat", "os.path.sep", "os.path.split", "os.path.splitdrive", "os.path.splitext", "os.path.stat", "os.path.supports_unicode_filenames", "os.path.sys", "sys", "test.libregrtest.main", /* "xml.dom", */ }; _Py_IDENTIFIER(stdout); _Py_IDENTIFIER(stderr); struct Yoinks { size_t n; char **p; } yoinks; static bool binonly; static int optimize; static char *pyfile; static char *outpath; static struct stat st; static PyObject *code; static PyObject *marsh; static bool nocompress; static bool isunittest; static bool insertrunner; static bool insertlauncher; static uint64_t image_base; static int strip_components; static struct ElfWriter *elf; static const char *path_prefix; static struct Interner *yoinked; static struct timespec timestamp; static struct Interner *forcepulls; static void GetOpts(int argc, char *argv[]) { int opt; image_base = IMAGE_BASE_VIRTUAL; path_prefix = ".python"; while ((opt = getopt(argc, argv, "hnmtr0Bb:O:o:C:P:Y:")) != -1) { switch (opt) { case 'B': binonly = true; break; case 't': isunittest = true; break; case '0': nocompress = true; break; case 'r': insertrunner = true; insertlauncher = false; break; case 'm': insertrunner = false; insertlauncher = true; break; case 'o': outpath = optarg; break; case 'P': path_prefix = optarg; break; case 'O': optimize = atoi(optarg); break; case 'C': strip_components = atoi(optarg); break; case 'b': image_base = strtoul(optarg, NULL, 0); break; case 'Y': yoinks.p = realloc(yoinks.p, ++yoinks.n * sizeof(*yoinks.p)); yoinks.p[yoinks.n - 1] = xstrdup(optarg); break; case 'n': exit(0); case 'h': fputs(MANUAL, stdout); exit(0); default: fputs(MANUAL, stderr); exit(1); } } if (argc - optind != 1) { fputs("error: need one input file\n", stderr); exit(1); } pyfile = argv[optind]; if (stat(pyfile, &st)) { perror(pyfile); exit(1); } if (!outpath) { outpath = xstrcat(pyfile, ".o"); } } static char * Dotify(char *s) { size_t i; for (i = 0; s[i]; ++i) { if (s[i] == '/') { s[i] = '.'; } } return s; } static char * GetZipFile(void) { const char *zipfile; zipfile = pyfile; zipfile = StripComponents(zipfile, strip_components); if (*path_prefix) { zipfile = gc(xjoinpaths(path_prefix, zipfile)); } return xstrdup(zipfile); } static char * GetZipDir(void) { return xstrcat(gc(xdirname(gc(GetZipFile()))), '/'); } static char * GetSynFile(void) { return xstrcat("/zip/", gc(GetZipFile())); } static char * GetModName(bool *ispkg) { char *mod; mod = Dotify(xstripexts(StripComponents(pyfile, strip_components))); if ((*ispkg = _endswith(mod, ".__init__"))) { mod[strlen(mod) - strlen(".__init__")] = 0; } return mod; } static bool IsDot(void) { bool res; char *mod; mod = Dotify(xstripexts(StripComponents(pyfile, strip_components))); res = !!strchr(mod, '.'); free(mod); return res; } static char * GetParent(void) { char *p; p = Dotify(xstripexts(StripComponents(pyfile, strip_components))); *strrchr(p, '.') = 0; return p; } static char * GetParent2(void) { char *p, *mod; mod = Dotify(xstripexts(StripComponents(pyfile, strip_components))); if (_endswith(mod, ".__init__")) mod[strlen(mod) - strlen(".__init__")] = 0; if ((p = strrchr(mod, '.'))) *p = 0; return mod; } static char * GetModSibling(const char *rel, long chomp) { char *p, *mod, *sib; mod = Dotify(xstripexts(StripComponents(pyfile, strip_components))); while (chomp-- > 0) { if ((p = strrchr(mod, '.'))) { *p = 0; } else { break; } } if (rel) { if (*mod) { sib = xstrcat(mod, '.', rel); } else { sib = xstrdup(rel); } } else { sib = xstrdup(mod); } free(mod); return sib; } static bool IsIgnoredModule(const char *s) { int m, l, r, x; l = 0; r = ARRAYLEN(kIgnoredModules) - 1; while (l <= r) { m = (l + r) >> 1; x = strcmp(s, kIgnoredModules[m]); if (x < 0) { r = m - 1; } else if (x > 0) { l = m + 1; } else { return true; } } return false; } static void Yoink(const char *name) { if (!isinterned(yoinked, name) && !IsIgnoredModule(name)) { intern(yoinked, name); /* elfwriter_yoink(elf, gc(xstrcat("pyc:", name)), STB_WEAK); */ } } static void Forcepull(const char *name) { if (!isinterned(forcepulls, name) && !IsIgnoredModule(name)) { intern(yoinked, name); intern(forcepulls, name); elfwriter_yoink(elf, gc(xstrcat("pyc:", name)), STB_GLOBAL); } } static void Provide(const char *modname, const char *global) { char *imp, *symbol; imp = xstrcat(modname, '.', global); if ((!isinterned(forcepulls, imp) && !isinterned(yoinked, imp) && !IsIgnoredModule(imp))) { symbol = xstrcat("pyc:", imp); elfwriter_appendsym(elf, symbol, ELF64_ST_INFO(STB_GLOBAL, STT_OBJECT), STV_DEFAULT, 0, 0); free(symbol); } free(imp); } static int Analyze(const char *modname, PyObject *code, struct Interner *globals) { int rc; bool istry; unsigned a; size_t i, j, n; char *p, *mod, *imp; int x, y, op, arg, rel; PyObject *co_code, *co_names, *co_consts, *name, *iter, *item; rc = 0; mod = 0; istry = rel = 0; assert(PyCode_Check(code)); co_code = ((PyCodeObject *)code)->co_code; co_names = ((PyCodeObject *)code)->co_names; co_consts = ((PyCodeObject *)code)->co_consts; n = PyBytes_GET_SIZE(co_code); p = PyBytes_AS_STRING(co_code); for (a = i = 0; !rc && i + 2 <= n; i += 2) { x = p[i + 0] & 255; y = p[i + 1] & 255; a = a << 8 | y; if ((op = x) == EXTENDED_ARG) continue; arg = a; switch (op) { case SETUP_EXCEPT: istry = true; break; case POP_BLOCK: istry = false; break; case LOAD_CONST: if ((item = PyTuple_GetItem(co_consts, arg))) { if (PyLong_Check(item)) { if ((rel = PyLong_AsLong(item)) == -1) { if (PyErr_Occurred()) { PyErr_Clear(); } } } } else { rc = -1; } break; case IMPORT_NAME: if (((item = PyTuple_GetItem(co_names, arg)) && (name = PyUnicode_AsUTF8String(item)))) { free(mod); if (*PyBytes_AS_STRING(name)) { if (rel) { mod = GetModSibling(PyBytes_AS_STRING(name), rel); } else { mod = xstrdup(PyBytes_AS_STRING(name)); } if (!IsIgnoredModule(mod)) { if (istry) { Yoink(mod); } else { Forcepull(mod); } } } else if (IsDot()) { if (rel) { mod = GetModSibling(0, rel); } else { mod = GetParent(); } } else { mod = 0; } Py_DECREF(name); } else { rc = -1; } break; case IMPORT_FROM: if (((item = PyTuple_GetItem(co_names, arg)) && (name = PyUnicode_AsUTF8String(item)))) { if (mod) { imp = xstrcat(mod, '.', PyBytes_AS_STRING(name)); } else { imp = xstrdup(PyBytes_AS_STRING(name)); } if (!IsIgnoredModule(imp)) { if (istry) { Yoink(imp); } else { Forcepull(imp); } } Py_DECREF(name); free(imp); } else { rc = -1; } break; case STORE_NAME: case STORE_GLOBAL: if (globals) { if (((item = PyTuple_GetItem(co_names, arg)) && (name = PyUnicode_AsUTF8String(item)))) { intern(globals, PyBytes_AS_STRING(name)); Py_DECREF(name); } else { rc = -1; } } break; default: break; } a = 0; } free(mod); if (!rc) { if ((iter = PyObject_GetIter(co_consts))) { while (!rc && (item = PyIter_Next(iter))) { if (PyCode_Check(item)) { rc |= Analyze(modname, item, 0); } Py_DECREF(item); } Py_DECREF(iter); if (!rc && PyErr_Occurred()) { rc = -1; } } else { rc = -1; } } return rc; } static int AnalyzeModule(const char *modname) { int rc; char *p; struct Interner *globals; globals = newinterner(); intern(globals, "__file__"); if (!(rc = Analyze(modname, code, globals))) { for (p = globals->p; *p; p += strlen(p) + 1) { Provide(modname, p); } } freeinterner(globals); return rc; } static int Objectify(void) { int rc; bool ispkg; size_t i, n; char header[12]; size_t pysize, pycsize, marsize; char *pydata, *pycdata, *mardata, *zipfile, *zipdir, *synfile, *modname; zipdir = gc(GetZipDir()); zipfile = gc(GetZipFile()); synfile = gc(GetSynFile()); modname = gc(GetModName(&ispkg)); CHECK_NOTNULL((pydata = gc(xslurp(pyfile, &pysize)))); if ((!(code = Py_CompileStringExFlags(pydata, synfile, Py_file_input, NULL, optimize)) || !(marsh = PyMarshal_WriteObjectToString(code, Py_MARSHAL_VERSION)))) { return -1; } assert(PyBytes_CheckExact(marsh)); mardata = PyBytes_AS_STRING(marsh); marsize = PyBytes_GET_SIZE(marsh); WRITE16LE(header+0, 3390); /* Python 3.7a1 */ WRITE16LE(header+2, READ16LE("\r\n")); WRITE32LE(header+4, timestamp.tv_sec); WRITE32LE(header+8, marsize); pycsize = sizeof(header) + marsize; pycdata = gc(malloc(pycsize)); memcpy(pycdata, header, sizeof(header)); memcpy(pycdata + sizeof(header), mardata, marsize); yoinked = newinterner(); forcepulls = newinterner(); elf = elfwriter_open(outpath, 0644); elfwriter_cargoculting(elf); if (ispkg) { elfwriter_zip(elf, zipdir, zipdir, strlen(zipdir), pydata, 0, 040755, timestamp, timestamp, timestamp, nocompress, image_base, kZipCdirHdrLinkableSize); } if (!binonly) { elfwriter_zip(elf, gc(xstrcat("py:", modname)), zipfile, strlen(zipfile), pydata, pysize, st.st_mode, timestamp, timestamp, timestamp, nocompress, image_base, kZipCdirHdrLinkableSize); } elfwriter_zip(elf, gc(xstrcat("pyc:", modname)), gc(xstrcat(zipfile, 'c')), strlen(zipfile) + 1, pycdata, pycsize, st.st_mode, timestamp, timestamp, timestamp, nocompress, image_base, kZipCdirHdrLinkableSize); elfwriter_align(elf, 1, 0); elfwriter_startsection(elf, ".yoink", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR); if (!(rc = AnalyzeModule(modname))) { if (*path_prefix && !IsDot()) { elfwriter_yoink(elf, gc(xstrcat(path_prefix, "/")), STB_GLOBAL); } if (strchr(modname, '.')) { Forcepull(gc(GetParent2())); } for (i = 0; i < yoinks.n; ++i) { elfwriter_yoink(elf, yoinks.p[i], STB_GLOBAL); } if (insertrunner) { elfwriter_yoink(elf, "RunPythonModule", STB_GLOBAL); } else if (insertlauncher) { elfwriter_yoink(elf, "LaunchPythonModule", STB_GLOBAL); } if (isunittest) { elfwriter_yoink(elf, "testlib_quota_handlers", STB_GLOBAL); } elfwriter_finishsection(elf); if (insertrunner || insertlauncher) { n = strlen(modname) + 1; elfwriter_align(elf, 1, 0); elfwriter_startsection(elf, ".rodata.str1.1", SHT_PROGBITS, SHF_ALLOC | SHF_MERGE | SHF_STRINGS); memcpy(elfwriter_reserve(elf, n), modname, n); elfwriter_appendsym(elf, "kLaunchPythonModuleName", ELF64_ST_INFO(STB_GLOBAL, STT_OBJECT), STV_DEFAULT, 0, n); elfwriter_commit(elf, n); elfwriter_finishsection(elf); } } elfwriter_close(elf); freeinterner(forcepulls); freeinterner(yoinked); return rc; } int main(int argc, char *argv[]) { int ec; timestamp.tv_sec = 1647414000; /* determinism */ /* clock_gettime(CLOCK_REALTIME, &timestamp); */ GetOpts(argc, argv); Py_NoUserSiteDirectory++; Py_NoSiteFlag++; Py_IgnoreEnvironmentFlag++; Py_FrozenFlag++; _Py_InitializeEx_Private(1, 0); if (!Objectify()) { ec = 0; } else { PyErr_Print(); ec = 1; } Py_XDECREF(marsh); Py_XDECREF(code); if (Py_FinalizeEx() < 0 && !ec) ec = 120; return ec; }
22,841
736
jart/cosmopolitan
false
cosmopolitan/third_party/python/hello.py
print('hello world')
21
2
jart/cosmopolitan
false
cosmopolitan/third_party/python/chibicc.inc
#define Py_LIMITED_API #define PY_SSIZE_T_CLEAN #include "third_party/python/Include/Python.h"
95
4
jart/cosmopolitan
false
cosmopolitan/third_party/python/README.rst
This is Python version 3.6.14+ ============================== .. image:: https://travis-ci.org/python/cpython.svg?branch=3.6 :alt: CPython build status on Travis CI :target: https://travis-ci.org/python/cpython .. image:: https://ci.appveyor.com/api/projects/status/4mew1a93xdkbf5ua/branch/3.6?svg=true :alt: CPython build status on Appveyor :target: https://ci.appveyor.com/project/python/cpython/branch/3.6 .. image:: https://dev.azure.com/python/cpython/_apis/build/status/Azure%20Pipelines%20CI?branchName=3.6 :alt: CPython build status on Azure Pipelines :target: https://dev.azure.com/python/cpython/_build/latest?definitionId=4&branchName=3.6 .. image:: https://codecov.io/gh/python/cpython/branch/3.6/graph/badge.svg :alt: CPython code coverage on Codecov :target: https://codecov.io/gh/python/cpython Copyright (c) 2001-2021 Python Software Foundation. All rights reserved. See the end of this file for further copyright and license information. General Information ------------------- - Website: https://www.python.org - Source code: https://github.com/python/cpython - Issue tracker: https://bugs.python.org - Documentation: https://docs.python.org - Developer's Guide: https://devguide.python.org/ Contributing to CPython ----------------------- For more complete instructions on contributing to CPython development, see the `Developer Guide`_. .. _Developer Guide: https://devguide.python.org/ Using Python ------------ Installable Python kits, and information about using Python, are available at `python.org`_. .. _python.org: https://www.python.org/ Build Instructions ------------------ On Unix, Linux, BSD, macOS, and Cygwin:: ./configure make make test sudo make install This will install Python as ``python3``. You can pass many options to the configure script; run ``./configure --help`` to find out more. On macOS and Cygwin, the executable is called ``python.exe``; elsewhere it's just ``python``. If you are running on macOS with the latest updates installed, make sure to install openSSL or some other SSL software along with Homebrew or another package manager. If issues persist, see https://devguide.python.org/setup/#macos-and-os-x for more information. On macOS, if you have configured Python with ``--enable-framework``, you should use ``make frameworkinstall`` to do the installation. Note that this installs the Python executable in a place that is not normally on your PATH, you may want to set up a symlink in ``/usr/local/bin``. On Windows, see `PCbuild/readme.txt <https://github.com/python/cpython/blob/3.6/PCbuild/readme.txt>`_. If you wish, you can create a subdirectory and invoke configure from there. For example:: mkdir debug cd debug ../configure --with-pydebug make make test (This will fail if you *also* built at the top-level directory. You should do a ``make clean`` at the toplevel first.) To get an optimized build of Python, ``configure --enable-optimizations`` before you run ``make``. This sets the default make targets up to enable Profile Guided Optimization (PGO) and may be used to auto-enable Link Time Optimization (LTO) on some platforms. For more details, see the sections below. Profile Guided Optimization --------------------------- PGO takes advantage of recent versions of the GCC or Clang compilers. If used, either via ``configure --enable-optimizations`` above or by manually running ``make profile-opt`` regardless of configure flags it will do several steps. First, the entire Python directory is cleaned of temporary files that may have resulted in a previous compilation. Then, an instrumented version of the interpreter is built, using suitable compiler flags for each flavour. Note that this is just an intermediary step. The binary resulting from this step is not good for real life workloads as it has profiling instructions embedded inside. After this instrumented version of the interpreter is built, the Makefile will automatically run a training workload. This is necessary in order to profile the interpreter execution. Note also that any output, both stdout and stderr, that may appear at this step is suppressed. Finally, the last step is to rebuild the interpreter, using the information collected in the previous one. The end result will be a Python binary that is optimized and suitable for distribution or production installation. Link Time Optimization ---------------------- Enabled via configure's ``--with-lto`` flag. LTO takes advantage of the ability of recent compiler toolchains to optimize across the otherwise arbitrary ``.o`` file boundary when building final executables or shared libraries for additional performance gains. What's New ---------- We have a comprehensive overview of the changes in the `What's New in Python 3.6 <https://docs.python.org/3.6/whatsnew/3.6.html>`_ document. For a more detailed change log, read `Misc/NEWS <https://github.com/python/cpython/blob/3.6/Misc/NEWS.d>`_, but a full accounting of changes can only be gleaned from the `commit history <https://github.com/python/cpython/commits/3.6>`_. If you want to install multiple versions of Python see the section below entitled "Installing multiple versions". Documentation ------------- `Documentation for Python 3.6 <https://docs.python.org/3.6/>`_ is online, updated daily. It can also be downloaded in many formats for faster access. The documentation is downloadable in HTML, PDF, and reStructuredText formats; the latter version is primarily for documentation authors, translators, and people with special formatting requirements. For information about building Python's documentation, refer to `Doc/README.rst <https://github.com/python/cpython/blob/3.6/Doc/README.rst>`_. Converting From Python 2.x to 3.x --------------------------------- Significant backward incompatible changes were made for the release of Python 3.0, which may cause programs written for Python 2 to fail when run with Python 3. For more information about porting your code from Python 2 to Python 3, see the `Porting HOWTO <https://docs.python.org/3/howto/pyporting.html>`_. Testing ------- To test the interpreter, type ``make test`` in the top-level directory. The test set produces some output. You can generally ignore the messages about skipped tests due to optional features which can't be imported. If a message is printed about a failed test or a traceback or core dump is produced, something is wrong. By default, tests are prevented from overusing resources like disk space and memory. To enable these tests, run ``make testall``. If any tests fail, you can re-run the failing test(s) in verbose mode. For example, if ``test_os`` and ``test_gdb`` failed, you can run:: make test TESTOPTS="-v test_os test_gdb" If the failure persists and appears to be a problem with Python rather than your environment, you can `file a bug report <https://bugs.python.org>`_ and include relevant output from that command to show the issue. See `Running & Writing Tests <https://devguide.python.org/runtests/>`_ for more on running tests. Installing multiple versions ---------------------------- On Unix and Mac systems if you intend to install multiple versions of Python using the same installation prefix (``--prefix`` argument to the configure script) you must take care that your primary python executable is not overwritten by the installation of a different version. All files and directories installed using ``make altinstall`` contain the major and minor version and can thus live side-by-side. ``make install`` also creates ``${prefix}/bin/python3`` which refers to ``${prefix}/bin/pythonX.Y``. If you intend to install multiple versions using the same prefix you must decide which version (if any) is your "primary" version. Install that version using ``make install``. Install all other versions using ``make altinstall``. For example, if you want to install Python 2.7, 3.5, and 3.6 with 3.6 being the primary version, you would execute ``make install`` in your 3.6 build directory and ``make altinstall`` in the others. Issue Tracker and Mailing List ------------------------------ Bug reports are welcome! You can use the `issue tracker <https://bugs.python.org>`_ to report bugs, and/or submit pull requests `on GitHub <https://github.com/python/cpython>`_. You can also follow development discussion on the `python-dev mailing list <https://mail.python.org/mailman/listinfo/python-dev/>`_. Proposals for enhancement ------------------------- If you have a proposal to change Python, you may want to send an email to the comp.lang.python or `python-ideas`_ mailing lists for initial feedback. A Python Enhancement Proposal (PEP) may be submitted if your idea gains ground. All current PEPs, as well as guidelines for submitting a new PEP, are listed at `python.org/dev/peps/ <https://www.python.org/dev/peps/>`_. .. _python-ideas: https://mail.python.org/mailman/listinfo/python-ideas/ Release Schedule ---------------- See :pep:`494` for Python 3.6 release details. Copyright and License Information --------------------------------- Copyright (c) 2001-2021 Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. All rights reserved. Copyright (c) 1995-2001 Corporation for National Research Initiatives. All rights reserved. Copyright (c) 1991-1995 Stichting Mathematisch Centrum. All rights reserved. See the file "LICENSE" for information on the history of this software, terms & conditions for usage, and a DISCLAIMER OF ALL WARRANTIES. This Python distribution contains *no* GNU General Public License (GPL) code, so it may be used in proprietary projects. There are interfaces to some GNU code but these are entirely optional. All trademarks referenced herein are property of their respective holders.
9,878
262
jart/cosmopolitan
false
cosmopolitan/third_party/python/launch.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/siginfo.h" #include "libc/calls/ucontext.h" #include "libc/dce.h" #include "libc/intrin/kprintf.h" #include "libc/log/libfatal.internal.h" #include "libc/log/log.h" #include "libc/mem/mem.h" #include "libc/runtime/runtime.h" #include "libc/testlib/testlib.h" #include "libc/x/x.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/frameobject.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/pytime.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/warnings.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ #define USE_COSMO_CRASH MODE_DBG + 0 STATIC_YOINK("zip_uri_support"); PYTHON_YOINK("_bootlocale"); PYTHON_YOINK("_locale"); PYTHON_YOINK("encodings.aliases"); PYTHON_YOINK("encodings.latin_1"); PYTHON_YOINK("encodings.utf_8"); PYTHON_YOINK("launchpy"); extern char kLaunchPythonModuleName[]; /* generated by pyobj.com */ const struct _frozen *PyImport_FrozenModules = _PyImport_FrozenModules; struct _inittab *PyImport_Inittab = _PyImport_Inittab; int LaunchPythonModule(const char *name) { PyObject *mod, *runpy, *runmodule, *runargs, *result; if (!(runpy = PyImport_ImportModule("launchpy"))) { PyErr_Print(); return 123; } if (!(runmodule = PyObject_GetAttrString(runpy, "run_module_as_main"))) { PyErr_Print(); Py_DECREF(runpy); return 122; } if (!(mod = PyUnicode_DecodeUTF8(name, strlen(name), 0))) { PyErr_Print(); Py_DECREF(runpy); Py_DECREF(runmodule); return 121; } if (!(runargs = Py_BuildValue("(O)", mod))) { PyErr_Print(); Py_DECREF(runpy); Py_DECREF(runmodule); Py_DECREF(mod); return 119; } if (!(result = PyObject_Call(runmodule, runargs, NULL))) { PyErr_Print(); } Py_DECREF(runpy); Py_DECREF(runmodule); Py_DECREF(mod); Py_DECREF(runargs); if (!result) return 118; Py_DECREF(result); return 0; } #if USE_COSMO_CRASH void ShowCrashReportHook(int err, int fd, int sig, struct siginfo *si, ucontext_t *ctx) { PyObject *str; PyFrameObject *frame; kprintf("\nCalamity Occurred w/ Python\n"); for (frame = PyEval_GetFrame(); frame; frame = frame->f_back) { str = PyUnicode_AsUTF8String(frame->f_code->co_filename); kprintf("%s:%d\n", PyBytes_AS_STRING(str), frame->f_code->co_firstlineno/* frame->f_lineno */); Py_DECREF(str); } } #endif int main(int argc, char *argv[]) { size_t n; int i, sts; wchar_t *w; PyObject *a, *s; #if USE_COSMO_CRASH ShowCrashReports(); #endif Py_FrozenFlag++; Py_NoSiteFlag++; /* Py_VerboseFlag++; */ Py_NoUserSiteDirectory++; Py_IgnoreEnvironmentFlag++; Py_DontWriteBytecodeFlag++; Py_Initialize(); Py_LimitedPath(); if (!(a = PyList_New(argc))) return 127; for (i = 0; i < argc; ++i) { if (!(w = utf8to32(argv[i], -1, &n))) return 126; if (!(s = PyUnicode_FromWideChar(w, n))) return 125; PyList_SetItem(a, i, s); free(w); } if (PySys_SetObject("argv", a)) return 124; sts = LaunchPythonModule(kLaunchPythonModuleName); Py_Finalize(); return sts; }
4,923
140
jart/cosmopolitan
false
cosmopolitan/third_party/python/runpythonmodule.h
#ifndef COSMOPOLITAN_THIRD_PARTY_PYTHON_RUNPYTHONMODULE_H_ #define COSMOPOLITAN_THIRD_PARTY_PYTHON_RUNPYTHONMODULE_H_ #if !(__ASSEMBLER__ + __LINKER__ + 0) COSMOPOLITAN_C_START_ int RunPythonModule(int, char **); COSMOPOLITAN_C_END_ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */ #endif /* COSMOPOLITAN_THIRD_PARTY_PYTHON_RUNPYTHONMODULE_H_ */
346
11
jart/cosmopolitan
false
cosmopolitan/third_party/python/python.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/yoink.h" #include "third_party/python/runpythonmodule.h" #include "tool/args/args.h" // clang-format off PYTHON_YOINK("xed"); PYTHON_YOINK("xterm"); PYTHON_YOINK("encodings"); PYTHON_YOINK("encodings.aliases"); PYTHON_YOINK("encodings.ascii"); PYTHON_YOINK("encodings.idna"); PYTHON_YOINK("encodings.latin_1"); PYTHON_YOINK("encodings.utf_8"); PYTHON_YOINK("encodings.utf_8_sig"); PYTHON_YOINK("encodings.utf_16"); PYTHON_YOINK("encodings.utf_16_be"); PYTHON_YOINK("encodings.utf_16_le"); PYTHON_YOINK("encodings.utf_32"); PYTHON_YOINK("encodings.utf_32_be"); PYTHON_YOINK("encodings.utf_32_le"); PYTHON_YOINK("encodings.uu_codec"); PYTHON_YOINK("encodings.undefined"); PYTHON_YOINK("encodings.hex_codec"); PYTHON_YOINK("encodings.base64_codec"); PYTHON_YOINK("encodings.unicode_escape"); PYTHON_YOINK("encodings.unicode_internal"); PYTHON_YOINK("encodings.raw_unicode_escape"); PYTHON_YOINK("encodings.zlib_codec"); PYTHON_YOINK("encodings.big5"); PYTHON_YOINK("encodings.big5hkscs"); PYTHON_YOINK("encodings.bz2_codec"); PYTHON_YOINK("encodings.charmap"); PYTHON_YOINK("encodings.cp037"); PYTHON_YOINK("encodings.cp1006"); PYTHON_YOINK("encodings.cp1026"); PYTHON_YOINK("encodings.cp1125"); PYTHON_YOINK("encodings.cp1140"); PYTHON_YOINK("encodings.cp1250"); PYTHON_YOINK("encodings.cp1251"); PYTHON_YOINK("encodings.cp1252"); PYTHON_YOINK("encodings.cp1253"); PYTHON_YOINK("encodings.cp1254"); PYTHON_YOINK("encodings.cp1255"); PYTHON_YOINK("encodings.cp1256"); PYTHON_YOINK("encodings.cp1257"); PYTHON_YOINK("encodings.cp1258"); PYTHON_YOINK("encodings.cp273"); PYTHON_YOINK("encodings.cp424"); PYTHON_YOINK("encodings.cp437"); PYTHON_YOINK("encodings.cp500"); PYTHON_YOINK("encodings.cp720"); PYTHON_YOINK("encodings.cp737"); PYTHON_YOINK("encodings.cp775"); PYTHON_YOINK("encodings.cp850"); PYTHON_YOINK("encodings.cp852"); PYTHON_YOINK("encodings.cp855"); PYTHON_YOINK("encodings.cp856"); PYTHON_YOINK("encodings.cp857"); PYTHON_YOINK("encodings.cp858"); PYTHON_YOINK("encodings.cp860"); PYTHON_YOINK("encodings.cp861"); PYTHON_YOINK("encodings.cp862"); PYTHON_YOINK("encodings.cp863"); PYTHON_YOINK("encodings.cp864"); PYTHON_YOINK("encodings.cp865"); PYTHON_YOINK("encodings.cp866"); PYTHON_YOINK("encodings.cp869"); PYTHON_YOINK("encodings.cp874"); PYTHON_YOINK("encodings.cp875"); PYTHON_YOINK("encodings.cp932"); PYTHON_YOINK("encodings.cp949"); PYTHON_YOINK("encodings.cp950"); PYTHON_YOINK("encodings.euc_jis_2004"); PYTHON_YOINK("encodings.euc_jisx0213"); PYTHON_YOINK("encodings.euc_jp"); PYTHON_YOINK("encodings.euc_kr"); PYTHON_YOINK("encodings.gb18030"); PYTHON_YOINK("encodings.gb2312"); PYTHON_YOINK("encodings.gbk"); PYTHON_YOINK("encodings.hp_roman8"); PYTHON_YOINK("encodings.hz"); PYTHON_YOINK("encodings.iso2022_jp"); PYTHON_YOINK("encodings.iso2022_jp_1"); PYTHON_YOINK("encodings.iso2022_jp_2"); PYTHON_YOINK("encodings.iso2022_jp_2004"); PYTHON_YOINK("encodings.iso2022_jp_3"); PYTHON_YOINK("encodings.iso2022_jp_ext"); PYTHON_YOINK("encodings.iso2022_kr"); PYTHON_YOINK("encodings.iso8859_1"); PYTHON_YOINK("encodings.iso8859_10"); PYTHON_YOINK("encodings.iso8859_11"); PYTHON_YOINK("encodings.iso8859_13"); PYTHON_YOINK("encodings.iso8859_14"); PYTHON_YOINK("encodings.iso8859_15"); PYTHON_YOINK("encodings.iso8859_16"); PYTHON_YOINK("encodings.iso8859_2"); PYTHON_YOINK("encodings.iso8859_3"); PYTHON_YOINK("encodings.iso8859_4"); PYTHON_YOINK("encodings.iso8859_5"); PYTHON_YOINK("encodings.iso8859_6"); PYTHON_YOINK("encodings.iso8859_7"); PYTHON_YOINK("encodings.iso8859_8"); PYTHON_YOINK("encodings.iso8859_9"); PYTHON_YOINK("encodings.johab"); PYTHON_YOINK("encodings.koi8_r"); PYTHON_YOINK("encodings.koi8_t"); PYTHON_YOINK("encodings.koi8_u"); PYTHON_YOINK("encodings.kz1048"); PYTHON_YOINK("encodings.mac_arabic"); PYTHON_YOINK("encodings.mac_centeuro"); PYTHON_YOINK("encodings.mac_croatian"); PYTHON_YOINK("encodings.mac_cyrillic"); PYTHON_YOINK("encodings.mac_farsi"); PYTHON_YOINK("encodings.mac_greek"); PYTHON_YOINK("encodings.mac_iceland"); PYTHON_YOINK("encodings.mac_latin2"); PYTHON_YOINK("encodings.mac_roman"); PYTHON_YOINK("encodings.mac_romanian"); PYTHON_YOINK("encodings.mac_turkish"); PYTHON_YOINK("encodings.palmos"); PYTHON_YOINK("encodings.ptcp154"); PYTHON_YOINK("encodings.punycode"); PYTHON_YOINK("encodings.quopri_codec"); PYTHON_YOINK("encodings.rot_13"); PYTHON_YOINK("encodings.shift_jis"); PYTHON_YOINK("encodings.shift_jis_2004"); PYTHON_YOINK("encodings.shift_jisx0213"); PYTHON_YOINK("encodings.tis_620"); PYTHON_YOINK("encodings.utf_7"); #ifndef TINY PYTHON_YOINK("pydoc_data.topics"); STATIC_YOINK(".python/pydoc_data/_pydoc.css"); #endif /* todo(jart): delete nonessential yoinks */ STATIC_YOINK("_PyImport_Inittab__bisect"); STATIC_YOINK("_PyImport_Inittab__codecs_cn"); STATIC_YOINK("_PyImport_Inittab__codecs_hk"); STATIC_YOINK("_PyImport_Inittab__codecs_iso2022"); STATIC_YOINK("_PyImport_Inittab__codecs_jp"); STATIC_YOINK("_PyImport_Inittab__codecs_kr"); STATIC_YOINK("_PyImport_Inittab__codecs_tw"); STATIC_YOINK("_PyImport_Inittab__csv"); STATIC_YOINK("_PyImport_Inittab__datetime"); STATIC_YOINK("_PyImport_Inittab__decimal"); STATIC_YOINK("_PyImport_Inittab__elementtree"); STATIC_YOINK("_PyImport_Inittab__json"); STATIC_YOINK("_PyImport_Inittab__lsprof"); STATIC_YOINK("_PyImport_Inittab__multibytecodec"); STATIC_YOINK("_PyImport_Inittab__multiprocessing"); STATIC_YOINK("_PyImport_Inittab__opcode"); STATIC_YOINK("_PyImport_Inittab__pickle"); STATIC_YOINK("_PyImport_Inittab__posixsubprocess"); STATIC_YOINK("_PyImport_Inittab__random"); STATIC_YOINK("_PyImport_Inittab__socket"); STATIC_YOINK("_PyImport_Inittab__sqlite3"); STATIC_YOINK("_PyImport_Inittab__stat"); STATIC_YOINK("_PyImport_Inittab__struct"); STATIC_YOINK("_PyImport_Inittab__symtable"); STATIC_YOINK("_PyImport_Inittab__testcapi"); STATIC_YOINK("_PyImport_Inittab__tracemalloc"); STATIC_YOINK("_PyImport_Inittab_array"); STATIC_YOINK("_PyImport_Inittab_atexit"); STATIC_YOINK("_PyImport_Inittab_audioop"); STATIC_YOINK("_PyImport_Inittab_binascii"); STATIC_YOINK("_PyImport_Inittab_cmath"); STATIC_YOINK("_PyImport_Inittab_faulthandler"); STATIC_YOINK("_PyImport_Inittab_fcntl"); STATIC_YOINK("_PyImport_Inittab_fpectl"); STATIC_YOINK("_PyImport_Inittab_grp"); STATIC_YOINK("_PyImport_Inittab_math"); STATIC_YOINK("_PyImport_Inittab_mmap"); STATIC_YOINK("_PyImport_Inittab_parser"); STATIC_YOINK("_PyImport_Inittab_pwd"); STATIC_YOINK("_PyImport_Inittab_pyexpat"); STATIC_YOINK("_PyImport_Inittab_resource"); STATIC_YOINK("_PyImport_Inittab_select"); STATIC_YOINK("_PyImport_Inittab_syslog"); STATIC_YOINK("_PyImport_Inittab_termios"); STATIC_YOINK("_PyImport_Inittab_time"); STATIC_YOINK("_PyImport_Inittab_unicodedata"); STATIC_YOINK("_PyImport_Inittab_zipimport"); PYTHON_YOINK("__future__"); PYTHON_YOINK("_bootlocale"); PYTHON_YOINK("_collections_abc"); PYTHON_YOINK("_compat_pickle"); PYTHON_YOINK("_compression"); PYTHON_YOINK("_dummy_thread"); PYTHON_YOINK("_markupbase"); PYTHON_YOINK("_pyio"); PYTHON_YOINK("_sitebuiltins"); PYTHON_YOINK("_strptime"); PYTHON_YOINK("_sysconfigdata_m_cosmo_x86_64_cosmo"); PYTHON_YOINK("_threading_local"); PYTHON_YOINK("_weakrefset"); PYTHON_YOINK("abc"); PYTHON_YOINK("argparse"); PYTHON_YOINK("ast"); PYTHON_YOINK("base64"); PYTHON_YOINK("bdb"); PYTHON_YOINK("binhex"); PYTHON_YOINK("bisect"); PYTHON_YOINK("calendar"); PYTHON_YOINK("chunk"); PYTHON_YOINK("cmd"); PYTHON_YOINK("code"); PYTHON_YOINK("codecs"); PYTHON_YOINK("colorsys"); PYTHON_YOINK("configparser"); PYTHON_YOINK("contextlib"); PYTHON_YOINK("copy"); PYTHON_YOINK("copyreg"); PYTHON_YOINK("csv"); PYTHON_YOINK("datetime"); PYTHON_YOINK("decimal"); PYTHON_YOINK("difflib"); PYTHON_YOINK("doctest"); PYTHON_YOINK("dummy_threading"); PYTHON_YOINK("threading"); PYTHON_YOINK("enum"); PYTHON_YOINK("filecmp"); PYTHON_YOINK("fileinput"); PYTHON_YOINK("fnmatch"); PYTHON_YOINK("formatter"); PYTHON_YOINK("fractions"); PYTHON_YOINK("functools"); PYTHON_YOINK("genericpath"); PYTHON_YOINK("getopt"); PYTHON_YOINK("getpass"); PYTHON_YOINK("gettext"); PYTHON_YOINK("glob"); PYTHON_YOINK("hashlib"); PYTHON_YOINK("heapq"); PYTHON_YOINK("hmac"); PYTHON_YOINK("imghdr"); PYTHON_YOINK("imp"); PYTHON_YOINK("io"); PYTHON_YOINK("ipaddress"); PYTHON_YOINK("keyword"); PYTHON_YOINK("linecache"); PYTHON_YOINK("locale"); PYTHON_YOINK("macpath"); PYTHON_YOINK("macurl2path"); PYTHON_YOINK("mimetypes"); PYTHON_YOINK("modulefinder"); PYTHON_YOINK("netrc"); PYTHON_YOINK("ntpath"); PYTHON_YOINK("nturl2path"); PYTHON_YOINK("numbers"); PYTHON_YOINK("opcode"); PYTHON_YOINK("operator"); PYTHON_YOINK("optparse"); PYTHON_YOINK("os"); PYTHON_YOINK("pathlib"); PYTHON_YOINK("pickle"); PYTHON_YOINK("pickletools"); PYTHON_YOINK("pipes"); PYTHON_YOINK("pkgutil"); PYTHON_YOINK("platform"); PYTHON_YOINK("plistlib"); PYTHON_YOINK("posixpath"); PYTHON_YOINK("pprint"); PYTHON_YOINK("pstats"); PYTHON_YOINK("pty"); PYTHON_YOINK("pyclbr"); PYTHON_YOINK("queue"); PYTHON_YOINK("quopri"); PYTHON_YOINK("random"); PYTHON_YOINK("re"); PYTHON_YOINK("reprlib"); PYTHON_YOINK("runpy"); PYTHON_YOINK("sched"); PYTHON_YOINK("secrets"); PYTHON_YOINK("selectors"); PYTHON_YOINK("shelve"); PYTHON_YOINK("shlex"); PYTHON_YOINK("shutil"); PYTHON_YOINK("signal"); PYTHON_YOINK("site"); PYTHON_YOINK("sndhdr"); PYTHON_YOINK("socket"); PYTHON_YOINK("socketserver"); PYTHON_YOINK("sre_compile"); PYTHON_YOINK("sre_constants"); PYTHON_YOINK("sre_parse"); PYTHON_YOINK("stat"); PYTHON_YOINK("statistics"); PYTHON_YOINK("string"); PYTHON_YOINK("stringprep"); PYTHON_YOINK("struct"); PYTHON_YOINK("subprocess"); PYTHON_YOINK("symbol"); PYTHON_YOINK("symtable"); PYTHON_YOINK("sysconfig"); PYTHON_YOINK("tabnanny"); PYTHON_YOINK("tempfile"); PYTHON_YOINK("textwrap"); PYTHON_YOINK("this"); PYTHON_YOINK("token"); PYTHON_YOINK("tokenize"); PYTHON_YOINK("trace"); PYTHON_YOINK("traceback"); PYTHON_YOINK("tty"); PYTHON_YOINK("types"); PYTHON_YOINK("typing"); PYTHON_YOINK("uu"); PYTHON_YOINK("uuid"); PYTHON_YOINK("warnings"); PYTHON_YOINK("weakref"); PYTHON_YOINK("webbrowser"); PYTHON_YOINK("xdrlib"); PYTHON_YOINK("aifc"); PYTHON_YOINK("wave"); PYTHON_YOINK("sunau"); PYTHON_YOINK("dis"); PYTHON_YOINK("codeop"); PYTHON_YOINK("compileall"); PYTHON_YOINK("py_compile"); PYTHON_YOINK("cgi"); PYTHON_YOINK("pdb"); PYTHON_YOINK("cgitb"); PYTHON_YOINK("pydoc"); PYTHON_YOINK("timeit"); PYTHON_YOINK("profile"); PYTHON_YOINK("inspect"); PYTHON_YOINK("cProfile"); PYTHON_YOINK("tracemalloc"); PYTHON_YOINK("bz2"); PYTHON_YOINK("gzip"); PYTHON_YOINK("zipapp"); PYTHON_YOINK("ftplib"); PYTHON_YOINK("tarfile"); PYTHON_YOINK("zipfile"); PYTHON_YOINK("telnetlib"); PYTHON_YOINK("antigravity"); PYTHON_YOINK("collections"); PYTHON_YOINK("collections.abc"); PYTHON_YOINK("json"); PYTHON_YOINK("json.decoder"); PYTHON_YOINK("json.encoder"); PYTHON_YOINK("json.scanner"); PYTHON_YOINK("json.tool"); PYTHON_YOINK("html"); PYTHON_YOINK("html.entities"); PYTHON_YOINK("html.parser"); PYTHON_YOINK("http"); PYTHON_YOINK("http.client"); PYTHON_YOINK("http.cookiejar"); PYTHON_YOINK("http.cookies"); PYTHON_YOINK("http.server"); PYTHON_YOINK("email"); PYTHON_YOINK("email._encoded_words"); PYTHON_YOINK("email._header_value_parser"); PYTHON_YOINK("email._parseaddr"); PYTHON_YOINK("email._policybase"); PYTHON_YOINK("email.base64mime"); PYTHON_YOINK("email.charset"); PYTHON_YOINK("email.contentmanager"); PYTHON_YOINK("email.encoders"); PYTHON_YOINK("email.errors"); PYTHON_YOINK("email.feedparser"); PYTHON_YOINK("email.generator"); PYTHON_YOINK("email.header"); PYTHON_YOINK("email.headerregistry"); PYTHON_YOINK("email.iterators"); PYTHON_YOINK("email.message"); PYTHON_YOINK("email.mime"); PYTHON_YOINK("email.mime.application"); PYTHON_YOINK("email.mime.audio"); PYTHON_YOINK("email.mime.base"); PYTHON_YOINK("email.mime.image"); PYTHON_YOINK("email.mime.message"); PYTHON_YOINK("email.mime.multipart"); PYTHON_YOINK("email.mime.nonmultipart"); PYTHON_YOINK("email.mime.text"); PYTHON_YOINK("email.parser"); PYTHON_YOINK("email.policy"); PYTHON_YOINK("email.quoprimime"); PYTHON_YOINK("email.utils"); STATIC_YOINK(".python/email/architecture.rst"); PYTHON_YOINK("importlib"); PYTHON_YOINK("importlib.abc"); PYTHON_YOINK("importlib.machinery"); PYTHON_YOINK("importlib.util"); PYTHON_YOINK("logging"); PYTHON_YOINK("logging.config"); PYTHON_YOINK("logging.handlers"); PYTHON_YOINK("urllib"); PYTHON_YOINK("urllib.error"); PYTHON_YOINK("urllib.parse"); PYTHON_YOINK("urllib.request"); PYTHON_YOINK("urllib.response"); PYTHON_YOINK("urllib.robotparser"); PYTHON_YOINK("wsgiref"); PYTHON_YOINK("wsgiref.handlers"); PYTHON_YOINK("wsgiref.headers"); PYTHON_YOINK("wsgiref.simple_server"); PYTHON_YOINK("wsgiref.util"); PYTHON_YOINK("wsgiref.validate"); PYTHON_YOINK("sqlite3"); PYTHON_YOINK("sqlite3.dbapi2"); PYTHON_YOINK("sqlite3.dump"); PYTHON_YOINK("xml"); PYTHON_YOINK("xml.dom.NodeFilter"); PYTHON_YOINK("xml.dom"); PYTHON_YOINK("xml.dom.domreg"); PYTHON_YOINK("xml.dom.expatbuilder"); PYTHON_YOINK("xml.dom.minicompat"); PYTHON_YOINK("xml.dom.minidom"); PYTHON_YOINK("xml.dom.pulldom"); PYTHON_YOINK("xml.dom.xmlbuilder"); PYTHON_YOINK("xml.etree.ElementInclude"); PYTHON_YOINK("xml.etree.ElementPath"); PYTHON_YOINK("xml.etree.ElementTree"); PYTHON_YOINK("xml.etree"); PYTHON_YOINK("xml.etree.cElementTree"); PYTHON_YOINK("xml.parsers"); PYTHON_YOINK("xml.parsers.expat"); PYTHON_YOINK("xml.sax"); PYTHON_YOINK("xml.sax._exceptions"); PYTHON_YOINK("xml.sax.expatreader"); PYTHON_YOINK("xml.sax.handler"); PYTHON_YOINK("xml.sax.saxutils"); PYTHON_YOINK("xml.sax.xmlreader"); PYTHON_YOINK("xmlrpc"); PYTHON_YOINK("xmlrpc.client"); PYTHON_YOINK("xmlrpc.server"); PYTHON_YOINK("multiprocessing"); PYTHON_YOINK("multiprocessing.connection"); PYTHON_YOINK("multiprocessing.context"); PYTHON_YOINK("multiprocessing.dummy"); PYTHON_YOINK("multiprocessing.dummy.connection"); PYTHON_YOINK("multiprocessing.forkserver"); PYTHON_YOINK("multiprocessing.heap"); PYTHON_YOINK("multiprocessing.managers"); PYTHON_YOINK("multiprocessing.pool"); PYTHON_YOINK("multiprocessing.popen_fork"); PYTHON_YOINK("multiprocessing.popen_forkserver"); PYTHON_YOINK("multiprocessing.popen_spawn_posix"); PYTHON_YOINK("multiprocessing.popen_spawn_win32"); PYTHON_YOINK("multiprocessing.process"); PYTHON_YOINK("multiprocessing.queues"); PYTHON_YOINK("multiprocessing.reduction"); PYTHON_YOINK("multiprocessing.resource_sharer"); PYTHON_YOINK("multiprocessing.semaphore_tracker"); PYTHON_YOINK("multiprocessing.spawn"); PYTHON_YOINK("multiprocessing.synchronize"); PYTHON_YOINK("multiprocessing.util"); PYTHON_YOINK("unittest"); PYTHON_YOINK("unittest.__main__"); PYTHON_YOINK("unittest.case"); PYTHON_YOINK("unittest.loader"); PYTHON_YOINK("unittest.main"); PYTHON_YOINK("unittest.mock"); PYTHON_YOINK("unittest.result"); PYTHON_YOINK("unittest.runner"); PYTHON_YOINK("unittest.signals"); PYTHON_YOINK("unittest.suite"); PYTHON_YOINK("unittest.util"); PYTHON_YOINK("smtpd"); PYTHON_YOINK("poplib"); PYTHON_YOINK("imaplib"); PYTHON_YOINK("mailbox"); PYTHON_YOINK("mailcap"); PYTHON_YOINK("smtplib"); PYTHON_YOINK("nntplib"); PYTHON_YOINK("asdl"); PYTHON_YOINK("_thread"); PYTHON_YOINK("_thread.LockType"); PYTHON_YOINK("_thread.RLock"); PYTHON_YOINK("_thread.TIMEOUT_MAX"); PYTHON_YOINK("_thread._count"); PYTHON_YOINK("_thread._local"); PYTHON_YOINK("_thread._set_sentinel"); PYTHON_YOINK("_thread.allocate"); PYTHON_YOINK("_thread.allocate_lock"); PYTHON_YOINK("_thread.error"); PYTHON_YOINK("_thread.exit"); PYTHON_YOINK("_thread.exit_thread"); PYTHON_YOINK("_thread.get_ident"); PYTHON_YOINK("_thread.interrupt_main"); PYTHON_YOINK("_thread.stack_size"); PYTHON_YOINK("_thread.start_new"); PYTHON_YOINK("_thread.start_new_thread"); PYTHON_YOINK("concurrent"); PYTHON_YOINK("concurrent.futures"); PYTHON_YOINK("concurrent.futures._base"); PYTHON_YOINK("concurrent.futures.process"); PYTHON_YOINK("concurrent.futures.thread"); PYTHON_YOINK("asynchat"); PYTHON_YOINK("asyncore"); PYTHON_YOINK("asyncio"); PYTHON_YOINK("asyncio.base_events"); PYTHON_YOINK("asyncio.base_futures"); PYTHON_YOINK("asyncio.base_subprocess"); PYTHON_YOINK("asyncio.base_tasks"); PYTHON_YOINK("asyncio.compat"); PYTHON_YOINK("asyncio.constants"); PYTHON_YOINK("asyncio.coroutines"); PYTHON_YOINK("asyncio.events"); PYTHON_YOINK("asyncio.futures"); PYTHON_YOINK("asyncio.locks"); PYTHON_YOINK("asyncio.log"); PYTHON_YOINK("asyncio.proactor_events"); PYTHON_YOINK("asyncio.protocols"); PYTHON_YOINK("asyncio.queues"); PYTHON_YOINK("asyncio.selector_events"); PYTHON_YOINK("asyncio.sslproto"); PYTHON_YOINK("asyncio.streams"); PYTHON_YOINK("asyncio.subprocess"); PYTHON_YOINK("asyncio.tasks"); PYTHON_YOINK("asyncio.transports"); PYTHON_YOINK("asyncio.unix_events"); int main(int argc, char **argv) { LoadZipArgs(&argc, &argv); return RunPythonModule(argc, argv); }
17,593
551
jart/cosmopolitan
false
cosmopolitan/third_party/python/.gitattributes
# -*- conf -*- *.com binary *.aif binary *.aifc binary *.aiff binary *.au binary *.bmp binary *.gif binary *.jpg binary *.pck binary *.png binary *.tar binary *.wav binary *.whl binary *.zip binary # Specific binary files Lib/test/sndhdrdata/sndhdr.* binary # Text files that should not be subject to eol conversion Lib/test/cjkencodings/* -text Lib/test/decimaltestdata/*.decTest -text Lib/test/test_email/data/*.txt -text Lib/test/xmltestdata/* -text Lib/test/coding20731.py -text # Special files in third party code Modules/zlib/zlib.map -text # CRLF files *.bat text eol=crlf *.ps1 text eol=crlf *.sln text eol=crlf *.vcxproj* text eol=crlf *.props text eol=crlf *.proj text eol=crlf PCbuild/readme.txt text eol=crlf PC/readme.txt text eol=crlf # Generated files # https://github.com/github/linguist#generated-code Include/graminit.h linguist-generated=true Python/graminit.h linguist-generated=true Modules/clinic/*.h linguist-generated=true Objects/clinic/*.h linguist-generated=true PC/clinic/*.h linguist-generated=true Python/clinic/*.h linguist-generated=true Python/importlib.h linguist-generated=true Python/importlib_external.h linguist-generated=true Include/Python-ast.h linguist-generated=true Python/Python-ast.c linguist-generated=true Include/opcode.h linguist-generated=true Python/opcode_targets.h linguist-generated=true Objects/typeslots.inc linguist-generated=true Modules/unicodedata_db.h linguist-generated=true
1,552
56
jart/cosmopolitan
false
cosmopolitan/third_party/python/python.mk
#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐ #───vi: set et ft=make ts=8 tw=8 fenc=utf-8 :vi───────────────────────┘ PKGS += THIRD_PARTY_PYTHON THIRD_PARTY_PYTHON_ARTIFACTS = \ THIRD_PARTY_PYTHON_STAGE1_A \ THIRD_PARTY_PYTHON_STAGE2_A \ THIRD_PARTY_PYTHON_PYTEST_A \ THIRD_PARTY_PYTHON_PYTHON \ THIRD_PARTY_PYTHON_FREEZE THIRD_PARTY_PYTHON_BINS = \ $(THIRD_PARTY_PYTHON_COMS) \ $(THIRD_PARTY_PYTHON_COMS:%=%.dbg) THIRD_PARTY_PYTHON_COMS = \ o/$(MODE)/third_party/python/Parser/asdl_c.com \ o/$(MODE)/third_party/python/pystone.com \ o/$(MODE)/third_party/python/python.com \ o/$(MODE)/third_party/python/freeze.com \ o/$(MODE)/third_party/python/pycomp.com \ o/$(MODE)/third_party/python/pyobj.com \ o/$(MODE)/third_party/python/hello.com \ o/$(MODE)/third_party/python/repl.com THIRD_PARTY_PYTHON_CHECKS = \ $(THIRD_PARTY_PYTHON_STAGE1_A).pkg \ $(THIRD_PARTY_PYTHON_STAGE2_A).pkg \ $(THIRD_PARTY_PYTHON_PYTEST_A).pkg \ $(THIRD_PARTY_PYTHON_HDRS:%=o/$(MODE)/%.ok) \ o/$(MODE)/third_party/python/python.pkg \ o/$(MODE)/third_party/python/freeze.pkg # TODO: Deal with aarch64 under qemu not making execve() easy. ifeq ($(ARCH), x86_64) THIRD_PARTY_PYTHON_CHECKS += \ $(THIRD_PARTY_PYTHON_PYTEST_PYMAINS:%=o/$(MODE)/%.runs) endif ################################################################################ # STAGE ONE - BOOTSTRAPPING PYTHON THIRD_PARTY_PYTHON_STAGE1 = \ $(THIRD_PARTY_PYTHON_STAGE1_A_DEPS) \ $(THIRD_PARTY_PYTHON_STAGE1_A) THIRD_PARTY_PYTHON_STAGE1_A = \ o/$(MODE)/third_party/python/python-stage1.a THIRD_PARTY_PYTHON_STAGE1_A_OBJS = \ $(THIRD_PARTY_PYTHON_STAGE1_A_SRCS:%.c=o/$(MODE)/%.o) THIRD_PARTY_PYTHON_HDRS = \ third_party/python/runpythonmodule.h \ third_party/python/Include/ezprint.h \ third_party/python/Include/yoink.h \ third_party/python/Include/object.h \ third_party/python/Include/Python-ast.h \ third_party/python/Include/Python.h \ third_party/python/Include/abstract.h \ third_party/python/Include/accu.h \ third_party/python/Include/asdl.h \ third_party/python/Include/ast.h \ third_party/python/Include/bitset.h \ third_party/python/Include/bltinmodule.h \ third_party/python/Include/boolobject.h \ third_party/python/Include/bytearrayobject.h \ third_party/python/Include/bytes_methods.h \ third_party/python/Include/bytesobject.h \ third_party/python/Include/cellobject.h \ third_party/python/Include/ceval.h \ third_party/python/Include/classobject.h \ third_party/python/Include/code.h \ third_party/python/Include/codecs.h \ third_party/python/Include/compile.h \ third_party/python/Include/complexobject.h \ third_party/python/Include/cosmo.h \ third_party/python/Include/datetime.h \ third_party/python/Include/descrobject.h \ third_party/python/Include/dictobject.h \ third_party/python/Include/dtoa.h \ third_party/python/Include/dynamic_annotations.h \ third_party/python/Include/enumobject.h \ third_party/python/Include/errcode.h \ third_party/python/Include/eval.h \ third_party/python/Include/fileobject.h \ third_party/python/Include/fileutils.h \ third_party/python/Include/floatobject.h \ third_party/python/Include/frameobject.h \ third_party/python/Include/funcobject.h \ third_party/python/Include/genobject.h \ third_party/python/Include/graminit.h \ third_party/python/Include/grammar.h \ third_party/python/Include/import.h \ third_party/python/Include/intrcheck.h \ third_party/python/Include/iterobject.h \ third_party/python/Include/listobject.h \ third_party/python/Include/longintrepr.h \ third_party/python/Include/longobject.h \ third_party/python/Include/marshal.h \ third_party/python/Include/memoryobject.h \ third_party/python/Include/metagrammar.h \ third_party/python/Include/methodobject.h \ third_party/python/Include/modsupport.h \ third_party/python/Include/moduleobject.h \ third_party/python/Include/namespaceobject.h \ third_party/python/Include/node.h \ third_party/python/Include/objimpl.h \ third_party/python/Include/odictobject.h \ third_party/python/Include/op.h \ third_party/python/Include/opcode.h \ third_party/python/Include/osdefs.h \ third_party/python/Include/osmodule.h \ third_party/python/Include/parsetok.h \ third_party/python/Include/patchlevel.h \ third_party/python/Include/pgen.h \ third_party/python/Include/pgenheaders.h \ third_party/python/Include/pyarena.h \ third_party/python/Include/pyatomic.h \ third_party/python/Include/pycapsule.h \ third_party/python/Include/pyctype.h \ third_party/python/Include/pydebug.h \ third_party/python/Include/pydtrace.h \ third_party/python/Include/pyerrors.h \ third_party/python/Include/pyexpat.h \ third_party/python/Include/pyfpe.h \ third_party/python/Include/pygetopt.h \ third_party/python/Include/pyhash.h \ third_party/python/Include/pylifecycle.h \ third_party/python/Include/pymacro.h \ third_party/python/Include/pymath.h \ third_party/python/Include/pymem.h \ third_party/python/Include/pyport.h \ third_party/python/Include/pystate.h \ third_party/python/Include/pystrcmp.h \ third_party/python/Include/pystrhex.h \ third_party/python/Include/pystrtod.h \ third_party/python/Include/pythonrun.h \ third_party/python/Include/pythread.h \ third_party/python/Include/pytime.h \ third_party/python/Include/rangeobject.h \ third_party/python/Include/setobject.h \ third_party/python/Include/sliceobject.h \ third_party/python/Include/structmember.h \ third_party/python/Include/structseq.h \ third_party/python/Include/symtable.h \ third_party/python/Include/sysmodule.h \ third_party/python/Include/token.h \ third_party/python/Include/traceback.h \ third_party/python/Include/tupleobject.h \ third_party/python/Include/typeslots.h \ third_party/python/Include/ucnhash.h \ third_party/python/Include/unicodeobject.h \ third_party/python/Include/warnings.h \ third_party/python/Include/weakrefobject.h \ third_party/python/Modules/unicodedata.h \ third_party/python/Modules/unicodedata_unidata.h \ third_party/python/Modules/_decimal/docstrings.h \ third_party/python/Modules/_decimal/libmpdec/basearith.h \ third_party/python/Modules/_decimal/libmpdec/bits.h \ third_party/python/Modules/_decimal/libmpdec/constants.h \ third_party/python/Modules/_decimal/libmpdec/convolute.h \ third_party/python/Modules/_decimal/libmpdec/crt.h \ third_party/python/Modules/_decimal/libmpdec/difradix2.h \ third_party/python/Modules/_decimal/libmpdec/fnt.h \ third_party/python/Modules/_decimal/libmpdec/fourstep.h \ third_party/python/Modules/_decimal/libmpdec/io.h \ third_party/python/Modules/_decimal/libmpdec/mpalloc.h \ third_party/python/Modules/_decimal/libmpdec/mpdecimal.h \ third_party/python/Modules/_decimal/libmpdec/numbertheory.h \ third_party/python/Modules/_decimal/libmpdec/sixstep.h \ third_party/python/Modules/_decimal/libmpdec/transpose.h \ third_party/python/Modules/_decimal/libmpdec/typearith.h \ third_party/python/Modules/_decimal/libmpdec/umodarith.h \ third_party/python/Modules/_io/_iomodule.h \ third_party/python/Modules/_math.h \ third_party/python/Modules/_multiprocessing/multiprocessing.h \ third_party/python/Modules/_sqlite/cache.h \ third_party/python/Modules/_sqlite/connection.h \ third_party/python/Modules/_sqlite/cursor.h \ third_party/python/Modules/_sqlite/microprotocols.h \ third_party/python/Modules/_sqlite/module.h \ third_party/python/Modules/_sqlite/prepare_protocol.h \ third_party/python/Modules/_sqlite/row.h \ third_party/python/Modules/_sqlite/statement.h \ third_party/python/Modules/_sqlite/util.h \ third_party/python/Modules/cjkcodecs/cjkcodecs.h \ third_party/python/Modules/cjkcodecs/multibytecodec.h \ third_party/python/Modules/cjkcodecs/somanyencodings.h \ third_party/python/Modules/expat/expat.h \ third_party/python/Modules/expat/expat_config.h \ third_party/python/Modules/expat/expat_external.h \ third_party/python/Modules/expat/pyexpatns.h \ third_party/python/Modules/expat/xmlrole.h \ third_party/python/Modules/expat/xmltok.h \ third_party/python/Modules/hashlib.h \ third_party/python/Modules/hashtable.h \ third_party/python/Modules/posixmodule.h \ third_party/python/Modules/rotatingtree.h \ third_party/python/Modules/socketmodule.h \ third_party/python/Modules/sre.h \ third_party/python/Modules/sre_constants.h \ third_party/python/Modules/winreparse.h \ third_party/python/Objects/dict-common.h \ third_party/python/Parser/parser.h \ third_party/python/Parser/tokenizer.h \ third_party/python/Python/condvar.h \ third_party/python/Python/importdl.h \ third_party/python/pyconfig.h THIRD_PARTY_PYTHON_INCS = \ third_party/python/chibicc.inc \ third_party/python/Objects/stringlib/localeutil.inc \ third_party/python/Objects/stringlib/unicodedefs.inc \ third_party/python/Objects/stringlib/replace.inc \ third_party/python/Objects/stringlib/unicode_format.inc \ third_party/python/Objects/stringlib/find_max_char.inc \ third_party/python/Objects/stringlib/find.inc \ third_party/python/Objects/stringlib/split.inc \ third_party/python/Objects/stringlib/transmogrify.inc \ third_party/python/Objects/stringlib/ucs1lib.inc \ third_party/python/Objects/stringlib/count.inc \ third_party/python/Objects/stringlib/undef.inc \ third_party/python/Objects/stringlib/partition.inc \ third_party/python/Objects/stringlib/ucs4lib.inc \ third_party/python/Objects/stringlib/asciilib.inc \ third_party/python/Objects/stringlib/eq.inc \ third_party/python/Objects/stringlib/ucs2lib.inc \ third_party/python/Objects/stringlib/join.inc \ third_party/python/Objects/stringlib/fastsearch.inc \ third_party/python/Objects/stringlib/ctype.inc \ third_party/python/Objects/stringlib/codecs.inc \ third_party/python/Objects/stringlib/stringdefs.inc \ third_party/python/Objects/clinic/bytearrayobject.inc \ third_party/python/Objects/clinic/unicodeobject.inc \ third_party/python/Objects/clinic/dictobject.inc \ third_party/python/Objects/clinic/bytesobject.inc \ third_party/python/Objects/typeslots.inc \ third_party/python/Python/thread_pthread.inc \ third_party/python/Python/opcode_targets.inc \ third_party/python/Python/wordcode_helpers.inc \ third_party/python/Python/ceval_gil.inc \ third_party/python/Python/clinic/import.inc \ third_party/python/Python/clinic/bltinmodule.inc \ third_party/python/Modules/expat/asciitab.inc \ third_party/python/Modules/expat/nametab.inc \ third_party/python/Modules/expat/utf8tab.inc \ third_party/python/Modules/expat/internal.inc \ third_party/python/Modules/expat/ascii.inc \ third_party/python/Modules/expat/xmltok_ns.inc \ third_party/python/Modules/expat/xmltok_impl.inc \ third_party/python/Modules/expat/siphash.inc \ third_party/python/Modules/expat/latin1tab.inc \ third_party/python/Modules/expat/xmltok_impl.h.inc \ third_party/python/Modules/expat/iasciitab.inc \ third_party/python/Modules/cjkcodecs/emu_jisx0213_2000.inc \ third_party/python/Modules/cjkcodecs/alg_jisx0201.inc \ third_party/python/Modules/cjkcodecs/clinic/multibytecodec.inc \ third_party/python/Modules/sre_lib.inc \ third_party/python/Modules/testcapi_long.inc \ third_party/python/Modules/_io/clinic/bufferedio.inc \ third_party/python/Modules/_io/clinic/bytesio.inc \ third_party/python/Modules/_io/clinic/iobase.inc \ third_party/python/Modules/_io/clinic/textio.inc \ third_party/python/Modules/_io/clinic/fileio.inc \ third_party/python/Modules/_io/clinic/stringio.inc \ third_party/python/Modules/_io/clinic/winconsoleio.inc \ third_party/python/Modules/_io/clinic/_iomodule.inc \ third_party/python/Modules/clinic/arraymodule.inc \ third_party/python/Modules/clinic/_datetimemodule.inc \ third_party/python/Modules/clinic/_lzmamodule.inc \ third_party/python/Modules/clinic/_weakref.inc \ third_party/python/Modules/clinic/posixmodule.inc \ third_party/python/Modules/clinic/zlibmodule.inc \ third_party/python/Modules/clinic/binascii.inc \ third_party/python/Modules/clinic/_bz2module.inc \ third_party/python/Modules/clinic/pyexpat.inc \ third_party/python/Modules/clinic/_opcode.inc \ third_party/python/Modules/clinic/_asynciomodule.inc \ third_party/python/Modules/clinic/_codecsmodule.inc \ third_party/python/Modules/clinic/unicodedata.inc \ third_party/python/Modules/clinic/grpmodule.inc \ third_party/python/Modules/clinic/spwdmodule.inc \ third_party/python/Modules/clinic/signalmodule.inc \ third_party/python/Modules/clinic/_cryptmodule.inc \ third_party/python/Modules/clinic/fcntlmodule.inc \ third_party/python/Modules/clinic/_sre.inc \ third_party/python/Modules/clinic/_cursesmodule.inc \ third_party/python/Modules/clinic/_winapi.inc \ third_party/python/Modules/clinic/_pickle.inc \ third_party/python/Modules/clinic/cmathmodule.inc \ third_party/python/Modules/clinic/_elementtree.inc \ third_party/python/Modules/clinic/pwdmodule.inc \ third_party/python/Modules/clinic/audioop.inc THIRD_PARTY_PYTHON_STAGE1_A_SRCS = \ third_party/python/Modules/_threadmodule.c \ third_party/python/Modules/_tracemalloc.c \ third_party/python/Modules/faulthandler.c \ third_party/python/Objects/abstract.c \ third_party/python/Modules/fspath.c \ third_party/python/Modules/gcmodule.c \ third_party/python/Modules/getbuildinfo.c \ third_party/python/Modules/getpath.c \ third_party/python/Modules/hashtable.c \ third_party/python/Modules/signalmodule.c \ third_party/python/Objects/boolobject.c \ third_party/python/Objects/bytearrayobject.c \ third_party/python/Objects/bytes_methods.c \ third_party/python/Objects/bytesobject.c \ third_party/python/Objects/capsule.c \ third_party/python/Objects/call.c \ third_party/python/Objects/cellobject.c \ third_party/python/Objects/classobject.c \ third_party/python/Objects/codeobject.c \ third_party/python/Objects/complexobject.c \ third_party/python/Objects/descrobject.c \ third_party/python/Objects/dictobject.c \ third_party/python/Objects/enumobject.c \ third_party/python/Objects/exceptions.c \ third_party/python/Objects/fileobject.c \ third_party/python/Objects/floatobject.c \ third_party/python/Objects/frameobject.c \ third_party/python/Objects/funcobject.c \ third_party/python/Objects/genobject.c \ third_party/python/Objects/iterobject.c \ third_party/python/Objects/listobject.c \ third_party/python/Objects/longobject.c \ third_party/python/Objects/memoryobject.c \ third_party/python/Objects/methodobject.c \ third_party/python/Objects/moduleobject.c \ third_party/python/Objects/namespaceobject.c \ third_party/python/Objects/object.c \ third_party/python/Objects/obmalloc.c \ third_party/python/Objects/odictobject.c \ third_party/python/Objects/rangeobject.c \ third_party/python/Objects/setobject.c \ third_party/python/Objects/sliceobject.c \ third_party/python/Objects/structseq.c \ third_party/python/Objects/tupleobject.c \ third_party/python/Objects/typeobject.c \ third_party/python/Objects/unicodectype.c \ third_party/python/Objects/unicodeobject.c \ third_party/python/Objects/weakrefobject.c \ third_party/python/Parser/acceler.c \ third_party/python/Parser/grammar1.c \ third_party/python/Parser/myreadline.c \ third_party/python/Parser/node.c \ third_party/python/Parser/parser.c \ third_party/python/Parser/parsetok.c \ third_party/python/Parser/tokenizer.c \ third_party/python/Python/Python-ast.c \ third_party/python/Python/_warnings.c \ third_party/python/Python/asdl.c \ third_party/python/Python/ast.c \ third_party/python/Python/bltinmodule.c \ third_party/python/Python/ceval.c \ third_party/python/Python/codecs.c \ third_party/python/Python/compile.c \ third_party/python/Python/cosmomodule.c \ third_party/python/Python/xtermmodule.c \ third_party/python/Python/xedmodule.c \ third_party/python/Python/dtoa.c \ third_party/python/Python/dynload_shlib.c \ third_party/python/Python/errors.c \ third_party/python/Python/fileutils.c \ third_party/python/Python/formatter_unicode.c \ third_party/python/Python/frozenmodules.c \ third_party/python/Python/future.c \ third_party/python/Python/getargs.c \ third_party/python/Python/getcompiler.c \ third_party/python/Python/getcopyright.c \ third_party/python/Python/getplatform.c \ third_party/python/Python/getversion.c \ third_party/python/Python/graminit.c \ third_party/python/Python/import.c \ third_party/python/Python/importdl.c \ third_party/python/Python/inittab.c \ third_party/python/Python/marshal.c \ third_party/python/Python/modsupport.c \ third_party/python/Python/mysnprintf.c \ third_party/python/Python/mystrtoul.c \ third_party/python/Python/peephole.c \ third_party/python/Python/pyarena.c \ third_party/python/Python/pyhash.c \ third_party/python/Python/pylifecycle.c \ third_party/python/Python/initstdio.c \ third_party/python/Python/initsite.c \ third_party/python/Python/initimport.c \ third_party/python/Python/initfsencoding.c \ third_party/python/Python/initsigs.c \ third_party/python/Python/initmain.c \ third_party/python/Python/finalize.c \ third_party/python/Python/initialized.c \ third_party/python/Python/atexit.c \ third_party/python/Python/flushstdfiles.c \ third_party/python/Python/progname.c \ third_party/python/Python/restoresigs.c \ third_party/python/Python/fdisinteractive.c \ third_party/python/Python/getsig.c \ third_party/python/Python/fatality.c \ third_party/python/Python/flags.c \ third_party/python/Python/pymath.c \ third_party/python/Python/pystate.c \ third_party/python/Python/pystrcmp.c \ third_party/python/Python/pystrhex.c \ third_party/python/Python/pystrtod.c \ third_party/python/Python/pythonrun.c \ third_party/python/Python/pytime.c \ third_party/python/Python/random.c \ third_party/python/Python/structmember.c \ third_party/python/Python/symtable.c \ third_party/python/Parser/listnode.c \ third_party/python/Python/sysmodule.c \ third_party/python/Python/thread.c \ third_party/python/Python/traceback.c \ third_party/python/Modules/unicodedata_3.2.0.c \ third_party/python/Modules/unicodedata_bidirectionalnames.c \ third_party/python/Modules/unicodedata_categorynames.c \ third_party/python/Modules/unicodedata_comp.c \ third_party/python/Modules/unicodedata_decomp.c \ third_party/python/Modules/unicodedata_decompprefix.c \ third_party/python/Modules/unicodedata_eastasianwidthnames.c \ third_party/python/Modules/unicodedata_getrecord.c \ third_party/python/Modules/unicodedata_isnormalized.c \ third_party/python/Modules/unicodedata_nfcfirst.c \ third_party/python/Modules/unicodedata_nfclast.c \ third_party/python/Modules/unicodedata_records.c \ third_party/python/Modules/unicodedata_namedsequences.c \ third_party/python/Modules/unicodedata_aliases.c \ third_party/python/Modules/unicodedata_lexicon.c \ third_party/python/Modules/unicodedata_phrasebook.c \ third_party/python/Modules/unicodedata_nfdnfkd.c \ third_party/python/Modules/unicodedata_nfcnfkc.c \ third_party/python/Modules/unicodedata_findnfcindex.c \ third_party/python/Modules/unicodedata_getcode.c \ third_party/python/Modules/unicodedata_codehash.c \ third_party/python/Modules/unicodedata_getdecomprecord.c \ third_party/python/Modules/unicodedata_isunifiedideograph.c \ third_party/python/Modules/unicodedata_iswhitespace.c \ third_party/python/Modules/unicodedata_islinebreak.c \ third_party/python/Modules/unicodedata_tonumeric.c \ third_party/python/Modules/unicodedata_extendedcase.c \ third_party/python/Modules/unicodedata_typerecords.c \ third_party/python/Modules/unicodedata_ucd.c THIRD_PARTY_PYTHON_STAGE1_A_DIRECTDEPS = \ DSP_SCALE \ LIBC_CALLS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_NT_KERNEL32 \ LIBC_RUNTIME \ LIBC_THREAD \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_SYSV_CALLS \ LIBC_TIME \ LIBC_TINYMATH \ LIBC_X \ TOOL_BUILD_LIB \ THIRD_PARTY_DLMALLOC \ THIRD_PARTY_GETOPT \ THIRD_PARTY_XED \ TOOL_ARGS THIRD_PARTY_PYTHON_STAGE1_A_DEPS = \ $(call uniq,$(foreach x,$(THIRD_PARTY_PYTHON_STAGE1_A_DIRECTDEPS),$($(x)))) o//third_party/python/Python/importlib.inc: \ $(VM) \ o/$(MODE)/third_party/python/freeze.com \ third_party/python/Lib/importlib/_bootstrap.py @$(COMPILE) -AFREEZE -wT$@ $^ $@ o//third_party/python/Python/importlib_external.inc: \ $(VM) \ o/$(MODE)/third_party/python/freeze.com \ third_party/python/Lib/importlib/_bootstrap_external.py @$(COMPILE) -AFREEZE -wT$@ $^ $@ $(THIRD_PARTY_PYTHON_STAGE1_A): \ $(THIRD_PARTY_PYTHON_STAGE1_A).pkg \ $(THIRD_PARTY_PYTHON_STAGE1_A_OBJS) $(THIRD_PARTY_PYTHON_STAGE1_A).pkg: \ $(THIRD_PARTY_PYTHON_STAGE1_A_OBJS) \ $(foreach x,$(THIRD_PARTY_PYTHON_STAGE1_A_DIRECTDEPS),$($(x)_A).pkg) ################################################################################ # STAGE TWO - PYTHON RUNTIME THIRD_PARTY_PYTHON_STAGE2 = \ $(THIRD_PARTY_PYTHON_STAGE2_A_DEPS) \ $(THIRD_PARTY_PYTHON_STAGE2_A) THIRD_PARTY_PYTHON_STAGE2_A = \ o/$(MODE)/third_party/python/python-stage2.a THIRD_PARTY_PYTHON_STAGE2_A_OBJS = \ $(THIRD_PARTY_PYTHON_STAGE2_A_SRCS:%.c=o/$(MODE)/%.o) \ $(THIRD_PARTY_PYTHON_STAGE2_A_PYS_OBJS) \ $(THIRD_PARTY_PYTHON_STAGE2_A_DATA_OBJS) THIRD_PARTY_PYTHON_STAGE2_A_PYS_OBJS = \ $(THIRD_PARTY_PYTHON_STAGE2_A_PYS:%.py=o/$(MODE)/%.o) THIRD_PARTY_PYTHON_STAGE2_A_DATA_OBJS = \ $(THIRD_PARTY_PYTHON_STAGE2_A_DATA:%=o/$(MODE)/%.zip.o) \ o/$(MODE)/third_party/python/Lib/.zip.o THIRD_PARTY_PYTHON_STAGE2_A_SRCS = \ third_party/python/runpythonmodule.c \ third_party/python/launch.c \ third_party/python/Objects/fromfd.c \ third_party/python/Objects/unicodeobject-deadcode.c \ third_party/python/Modules/_bisectmodule.c \ third_party/python/Modules/_bz2module.c \ third_party/python/Modules/_codecsmodule.c \ third_party/python/Modules/_collectionsmodule.c \ third_party/python/Modules/_csv.c \ third_party/python/Modules/_datetimemodule.c \ third_party/python/Modules/_decimal/_decimal.c \ third_party/python/Modules/_decimal/libmpdec/basearith.c \ third_party/python/Modules/_decimal/libmpdec/constants.c \ third_party/python/Modules/_decimal/libmpdec/context.c \ third_party/python/Modules/_decimal/libmpdec/convolute.c \ third_party/python/Modules/_decimal/libmpdec/crt.c \ third_party/python/Modules/_decimal/libmpdec/difradix2.c \ third_party/python/Modules/_decimal/libmpdec/fnt.c \ third_party/python/Modules/_decimal/libmpdec/fourstep.c \ third_party/python/Modules/_decimal/libmpdec/io.c \ third_party/python/Modules/_decimal/libmpdec/memory.c \ third_party/python/Modules/_decimal/libmpdec/mpdecimal.c \ third_party/python/Modules/_decimal/libmpdec/numbertheory.c \ third_party/python/Modules/_decimal/libmpdec/sixstep.c \ third_party/python/Modules/_decimal/libmpdec/transpose.c \ third_party/python/Modules/_elementtree.c \ third_party/python/Modules/_functoolsmodule.c \ third_party/python/Modules/_heapqmodule.c \ third_party/python/Modules/_io/_iomodule.c \ third_party/python/Modules/_io/bufferedio.c \ third_party/python/Modules/_io/bytesio.c \ third_party/python/Modules/_io/fileio.c \ third_party/python/Modules/_io/iobase.c \ third_party/python/Modules/_io/stringio.c \ third_party/python/Modules/_io/textio.c \ third_party/python/Modules/_hashmbedtls.c \ third_party/python/Modules/_json.c \ third_party/python/Modules/_multiprocessing/semaphore.c \ third_party/python/Modules/_multiprocessing/multiprocessing.c \ third_party/python/Modules/_localemodule.c \ third_party/python/Modules/_lsprof.c \ third_party/python/Modules/_math.c \ third_party/python/Modules/_opcode.c \ third_party/python/Modules/_operator.c \ third_party/python/Modules/_pickle.c \ third_party/python/Modules/_posixsubprocess.c \ third_party/python/Modules/_randommodule.c \ third_party/python/Modules/_sqlite/cache.c \ third_party/python/Modules/_sqlite/connection.c \ third_party/python/Modules/_sqlite/cursor.c \ third_party/python/Modules/_sqlite/microprotocols.c \ third_party/python/Modules/_sqlite/module.c \ third_party/python/Modules/_sqlite/prepare_protocol.c \ third_party/python/Modules/_sqlite/row.c \ third_party/python/Modules/_sqlite/statement.c \ third_party/python/Modules/_sqlite/util.c \ third_party/python/Modules/_sre.c \ third_party/python/Modules/_lol3.c \ third_party/python/Modules/_stat.c \ third_party/python/Modules/_struct.c \ third_party/python/Modules/_testcapimodule.c \ third_party/python/Modules/_tracemalloc.c \ third_party/python/Modules/_weakref.c \ third_party/python/Modules/arraymodule.c \ third_party/python/Modules/atexitmodule.c \ third_party/python/Modules/audioop.c \ third_party/python/Modules/binascii.c \ third_party/python/Modules/cjkcodecs/_codecs_cn.c \ third_party/python/Modules/cjkcodecs/_codecs_hk.c \ third_party/python/Modules/cjkcodecs/_codecs_iso2022.c \ third_party/python/Modules/cjkcodecs/_codecs_jp.c \ third_party/python/Modules/cjkcodecs/_codecs_kr.c \ third_party/python/Modules/cjkcodecs/_codecs_tw.c \ third_party/python/Modules/cjkcodecs/multibytecodec.c \ third_party/python/Modules/cjkcodecs/__big5_decmap.c \ third_party/python/Modules/cjkcodecs/big5_decmap.c \ third_party/python/Modules/cjkcodecs/__big5_encmap.c \ third_party/python/Modules/cjkcodecs/big5_encmap.c \ third_party/python/Modules/cjkcodecs/__cp950ext_decmap.c \ third_party/python/Modules/cjkcodecs/cp950ext_decmap.c \ third_party/python/Modules/cjkcodecs/__cp950ext_encmap.c \ third_party/python/Modules/cjkcodecs/cp950ext_encmap.c \ third_party/python/Modules/cjkcodecs/__big5hkscs_bmp_encmap.c \ third_party/python/Modules/cjkcodecs/big5hkscs_bmp_encmap.c \ third_party/python/Modules/cjkcodecs/__big5hkscs_nonbmp_encmap.c\ third_party/python/Modules/cjkcodecs/big5hkscs_nonbmp_encmap.c \ third_party/python/Modules/cjkcodecs/__gbcommon_encmap.c \ third_party/python/Modules/cjkcodecs/gbcommon_encmap.c \ third_party/python/Modules/cjkcodecs/__gb18030ext_encmap.c \ third_party/python/Modules/cjkcodecs/gb18030ext_encmap.c \ third_party/python/Modules/cjkcodecs/jisx0213_pair_encmap.c \ third_party/python/Modules/cjkcodecs/__jisxcommon_encmap.c \ third_party/python/Modules/cjkcodecs/jisxcommon_encmap.c \ third_party/python/Modules/cjkcodecs/__cp932ext_encmap.c \ third_party/python/Modules/cjkcodecs/cp932ext_encmap.c \ third_party/python/Modules/cjkcodecs/__jisx0213_bmp_encmap.c \ third_party/python/Modules/cjkcodecs/jisx0213_bmp_encmap.c \ third_party/python/Modules/cjkcodecs/__jisx0213_emp_encmap.c \ third_party/python/Modules/cjkcodecs/jisx0213_emp_encmap.c \ third_party/python/Modules/cjkcodecs/__big5_encmap.c \ third_party/python/Modules/cjkcodecs/big5_encmap.c \ third_party/python/Modules/cjkcodecs/__cp950ext_encmap.c \ third_party/python/Modules/cjkcodecs/cp950ext_encmap.c \ third_party/python/Modules/cjkcodecs/cp949_encmap.c \ third_party/python/Modules/cjkcodecs/__cp949_encmap.c \ third_party/python/Modules/cjkcodecs/__ksx1001_decmap.c \ third_party/python/Modules/cjkcodecs/ksx1001_decmap.c \ third_party/python/Modules/cjkcodecs/__cp949ext_decmap.c \ third_party/python/Modules/cjkcodecs/cp949ext_decmap.c \ third_party/python/Modules/cjkcodecs/__jisx0208_decmap.c \ third_party/python/Modules/cjkcodecs/jisx0208_decmap.c \ third_party/python/Modules/cjkcodecs/__jisx0212_decmap.c \ third_party/python/Modules/cjkcodecs/jisx0212_decmap.c \ third_party/python/Modules/cjkcodecs/__jisxcommon_encmap.c \ third_party/python/Modules/cjkcodecs/jisxcommon_encmap.c \ third_party/python/Modules/cjkcodecs/__cp932ext_decmap.c \ third_party/python/Modules/cjkcodecs/cp932ext_decmap.c \ third_party/python/Modules/cjkcodecs/__cp932ext_encmap.c \ third_party/python/Modules/cjkcodecs/cp932ext_encmap.c \ third_party/python/Modules/cjkcodecs/__jisx0213_1_bmp_decmap.c \ third_party/python/Modules/cjkcodecs/jisx0213_1_bmp_decmap.c \ third_party/python/Modules/cjkcodecs/__jisx0213_2_bmp_decmap.c \ third_party/python/Modules/cjkcodecs/jisx0213_2_bmp_decmap.c \ third_party/python/Modules/cjkcodecs/__jisx0213_bmp_encmap.c \ third_party/python/Modules/cjkcodecs/jisx0213_bmp_encmap.c \ third_party/python/Modules/cjkcodecs/__jisx0213_1_emp_decmap.c \ third_party/python/Modules/cjkcodecs/jisx0213_1_emp_decmap.c \ third_party/python/Modules/cjkcodecs/__jisx0213_2_emp_decmap.c \ third_party/python/Modules/cjkcodecs/jisx0213_2_emp_decmap.c \ third_party/python/Modules/cjkcodecs/__jisx0213_emp_encmap.c \ third_party/python/Modules/cjkcodecs/jisx0213_emp_encmap.c \ third_party/python/Modules/cjkcodecs/__jisx0213_pair_decmap.c \ third_party/python/Modules/cjkcodecs/jisx0213_pair_decmap.c \ third_party/python/Modules/cjkcodecs/jisx0213_pair_encmap.c \ third_party/python/Modules/cjkcodecs/__gb2312_decmap.c \ third_party/python/Modules/cjkcodecs/gb2312_decmap.c \ third_party/python/Modules/cjkcodecs/__gbkext_decmap.c \ third_party/python/Modules/cjkcodecs/gbkext_decmap.c \ third_party/python/Modules/cjkcodecs/__gbcommon_encmap.c \ third_party/python/Modules/cjkcodecs/gbcommon_encmap.c \ third_party/python/Modules/cjkcodecs/__gb18030ext_decmap.c \ third_party/python/Modules/cjkcodecs/gb18030ext_decmap.c \ third_party/python/Modules/cjkcodecs/__gb18030ext_encmap.c \ third_party/python/Modules/cjkcodecs/gb18030ext_encmap.c \ third_party/python/Modules/cjkcodecs/__big5hkscs_decmap.c \ third_party/python/Modules/cjkcodecs/big5hkscs_decmap.c \ third_party/python/Modules/cmathmodule.c \ third_party/python/Modules/config.c \ third_party/python/Modules/errnomodule.c \ third_party/python/Modules/expat/xmlparse.c \ third_party/python/Modules/expat/xmlrole.c \ third_party/python/Modules/expat/xmltok.c \ third_party/python/Modules/faulthandler.c \ third_party/python/Modules/fcntlmodule.c \ third_party/python/Modules/fpectlmodule.c \ third_party/python/Modules/fspath.c \ third_party/python/Modules/gcmodule.c \ third_party/python/Modules/getbuildinfo.c \ third_party/python/Modules/getpath.c \ third_party/python/Modules/grpmodule.c \ third_party/python/Modules/hashtable.c \ third_party/python/Modules/itertoolsmodule.c \ third_party/python/Modules/main.c \ third_party/python/Modules/mathmodule.c \ third_party/python/Modules/mmapmodule.c \ third_party/python/Modules/parsermodule.c \ third_party/python/Modules/posixmodule.c \ third_party/python/Modules/pwdmodule.c \ third_party/python/Modules/pyexpat.c \ third_party/python/Modules/resource.c \ third_party/python/Modules/rotatingtree.c \ third_party/python/Modules/selectmodule.c \ third_party/python/Modules/unicodedata.c \ third_party/python/Modules/signalmodule.c \ third_party/python/Modules/socketmodule.c \ third_party/python/Modules/tlsmodule.c \ third_party/python/Modules/symtablemodule.c \ third_party/python/Modules/syslogmodule.c \ third_party/python/Modules/syslogmodule.c \ third_party/python/Modules/termios.c \ third_party/python/Modules/timemodule.c \ third_party/python/Modules/zipimport.c \ third_party/python/Modules/zlibmodule.c \ third_party/python/Objects/accu.c \ third_party/python/Objects/weakrefobject.c \ third_party/python/Parser/bitset.c \ third_party/python/Parser/firstsets.c \ third_party/python/Parser/grammar.c \ third_party/python/Parser/metagrammar.c \ third_party/python/Parser/pgen.c \ third_party/python/Python/dynamic_annotations.c \ third_party/python/Python/recursive.c \ third_party/python/Python/frozen.c \ third_party/python/Python/frozenmain.c \ third_party/python/Python/getopt.c \ third_party/python/Python/pyfpe.c \ third_party/python/Python/sigcheck.c THIRD_PARTY_PYTHON_STAGE2_A_PYS = \ third_party/python/Parser/asdl.py \ third_party/python/Parser/asdl_c.py \ third_party/python/Lib/__future__.py \ third_party/python/Lib/_bootlocale.py \ third_party/python/Lib/_collections_abc.py \ third_party/python/Lib/_compat_pickle.py \ third_party/python/Lib/_compression.py \ third_party/python/Lib/_dummy_thread.py \ third_party/python/Lib/_markupbase.py \ third_party/python/Lib/_pydecimal.py \ third_party/python/Lib/_pyio.py \ third_party/python/Lib/_sitebuiltins.py \ third_party/python/Lib/_strptime.py \ third_party/python/Lib/_sysconfigdata_m_cosmo_x86_64_cosmo.py \ third_party/python/Lib/_threading_local.py \ third_party/python/Lib/_weakrefset.py \ third_party/python/Lib/asyncio/base_events.py \ third_party/python/Lib/asyncio/base_futures.py \ third_party/python/Lib/asyncio/base_subprocess.py \ third_party/python/Lib/asyncio/base_tasks.py \ third_party/python/Lib/asyncio/compat.py \ third_party/python/Lib/asyncio/constants.py \ third_party/python/Lib/asyncio/coroutines.py \ third_party/python/Lib/asyncio/events.py \ third_party/python/Lib/asyncio/futures.py \ third_party/python/Lib/asyncio/__init__.py \ third_party/python/Lib/asyncio/locks.py \ third_party/python/Lib/asyncio/log.py \ third_party/python/Lib/asyncio/proactor_events.py \ third_party/python/Lib/asyncio/protocols.py \ third_party/python/Lib/asyncio/queues.py \ third_party/python/Lib/asyncio/selector_events.py \ third_party/python/Lib/asyncio/sslproto.py \ third_party/python/Lib/asyncio/streams.py \ third_party/python/Lib/asyncio/subprocess.py \ third_party/python/Lib/asyncio/tasks.py \ third_party/python/Lib/asyncio/transports.py \ third_party/python/Lib/asyncio/unix_events.py \ third_party/python/Lib/abc.py \ third_party/python/Lib/aifc.py \ third_party/python/Lib/antigravity.py \ third_party/python/Lib/argparse.py \ third_party/python/Lib/ast.py \ third_party/python/Lib/asynchat.py \ third_party/python/Lib/asyncore.py \ third_party/python/Lib/base64.py \ third_party/python/Lib/bdb.py \ third_party/python/Lib/binhex.py \ third_party/python/Lib/bisect.py \ third_party/python/Lib/bz2.py \ third_party/python/Lib/cProfile.py \ third_party/python/Lib/calendar.py \ third_party/python/Lib/cgi.py \ third_party/python/Lib/cgitb.py \ third_party/python/Lib/chunk.py \ third_party/python/Lib/cmd.py \ third_party/python/Lib/code.py \ third_party/python/Lib/codecs.py \ third_party/python/Lib/codeop.py \ third_party/python/Lib/collections/__init__.py \ third_party/python/Lib/collections/abc.py \ third_party/python/Lib/colorsys.py \ third_party/python/Lib/compileall.py \ third_party/python/Lib/configparser.py \ third_party/python/Lib/contextlib.py \ third_party/python/Lib/copy.py \ third_party/python/Lib/copyreg.py \ third_party/python/Lib/csv.py \ third_party/python/Lib/datetime.py \ third_party/python/Lib/decimal.py \ third_party/python/Lib/difflib.py \ third_party/python/Lib/dis.py \ third_party/python/Lib/dummy_threading.py \ third_party/python/Lib/concurrent/__init__.py \ third_party/python/Lib/concurrent/futures/__init__.py \ third_party/python/Lib/concurrent/futures/process.py \ third_party/python/Lib/concurrent/futures/thread.py \ third_party/python/Lib/concurrent/futures/_base.py \ third_party/python/Lib/email/__init__.py \ third_party/python/Lib/email/_encoded_words.py \ third_party/python/Lib/email/_header_value_parser.py \ third_party/python/Lib/email/_parseaddr.py \ third_party/python/Lib/email/_policybase.py \ third_party/python/Lib/email/base64mime.py \ third_party/python/Lib/email/charset.py \ third_party/python/Lib/email/contentmanager.py \ third_party/python/Lib/email/encoders.py \ third_party/python/Lib/email/errors.py \ third_party/python/Lib/email/feedparser.py \ third_party/python/Lib/email/generator.py \ third_party/python/Lib/email/header.py \ third_party/python/Lib/email/headerregistry.py \ third_party/python/Lib/email/iterators.py \ third_party/python/Lib/email/message.py \ third_party/python/Lib/email/mime/__init__.py \ third_party/python/Lib/email/mime/application.py \ third_party/python/Lib/email/mime/audio.py \ third_party/python/Lib/email/mime/base.py \ third_party/python/Lib/email/mime/image.py \ third_party/python/Lib/email/mime/message.py \ third_party/python/Lib/email/mime/multipart.py \ third_party/python/Lib/email/mime/nonmultipart.py \ third_party/python/Lib/email/mime/text.py \ third_party/python/Lib/email/parser.py \ third_party/python/Lib/email/policy.py \ third_party/python/Lib/email/quoprimime.py \ third_party/python/Lib/email/utils.py \ third_party/python/Lib/encodings/__init__.py \ third_party/python/Lib/encodings/bz2_codec.py \ third_party/python/Lib/encodings/aliases.py \ third_party/python/Lib/encodings/ascii.py \ third_party/python/Lib/encodings/base64_codec.py \ third_party/python/Lib/encodings/big5.py \ third_party/python/Lib/encodings/big5hkscs.py \ third_party/python/Lib/encodings/charmap.py \ third_party/python/Lib/encodings/cp037.py \ third_party/python/Lib/encodings/cp1006.py \ third_party/python/Lib/encodings/cp1026.py \ third_party/python/Lib/encodings/cp1125.py \ third_party/python/Lib/encodings/cp1140.py \ third_party/python/Lib/encodings/cp1250.py \ third_party/python/Lib/encodings/cp1251.py \ third_party/python/Lib/encodings/cp1252.py \ third_party/python/Lib/encodings/cp1253.py \ third_party/python/Lib/encodings/cp1254.py \ third_party/python/Lib/encodings/cp1255.py \ third_party/python/Lib/encodings/cp1256.py \ third_party/python/Lib/encodings/cp1257.py \ third_party/python/Lib/encodings/cp1258.py \ third_party/python/Lib/encodings/cp273.py \ third_party/python/Lib/encodings/cp424.py \ third_party/python/Lib/encodings/cp437.py \ third_party/python/Lib/encodings/cp500.py \ third_party/python/Lib/encodings/cp65001.py \ third_party/python/Lib/encodings/cp720.py \ third_party/python/Lib/encodings/cp737.py \ third_party/python/Lib/encodings/cp775.py \ third_party/python/Lib/encodings/cp850.py \ third_party/python/Lib/encodings/cp852.py \ third_party/python/Lib/encodings/cp855.py \ third_party/python/Lib/encodings/cp856.py \ third_party/python/Lib/encodings/cp857.py \ third_party/python/Lib/encodings/cp858.py \ third_party/python/Lib/encodings/cp860.py \ third_party/python/Lib/encodings/cp861.py \ third_party/python/Lib/encodings/cp862.py \ third_party/python/Lib/encodings/cp863.py \ third_party/python/Lib/encodings/cp864.py \ third_party/python/Lib/encodings/cp865.py \ third_party/python/Lib/encodings/cp866.py \ third_party/python/Lib/encodings/cp869.py \ third_party/python/Lib/encodings/cp874.py \ third_party/python/Lib/encodings/cp875.py \ third_party/python/Lib/encodings/cp932.py \ third_party/python/Lib/encodings/cp949.py \ third_party/python/Lib/encodings/cp950.py \ third_party/python/Lib/encodings/euc_jis_2004.py \ third_party/python/Lib/encodings/euc_jisx0213.py \ third_party/python/Lib/encodings/euc_jp.py \ third_party/python/Lib/encodings/euc_kr.py \ third_party/python/Lib/encodings/gb18030.py \ third_party/python/Lib/encodings/gb2312.py \ third_party/python/Lib/encodings/gbk.py \ third_party/python/Lib/encodings/hex_codec.py \ third_party/python/Lib/encodings/hp_roman8.py \ third_party/python/Lib/encodings/hz.py \ third_party/python/Lib/encodings/idna.py \ third_party/python/Lib/encodings/iso2022_jp.py \ third_party/python/Lib/encodings/iso2022_jp_1.py \ third_party/python/Lib/encodings/iso2022_jp_2.py \ third_party/python/Lib/encodings/iso2022_jp_2004.py \ third_party/python/Lib/encodings/iso2022_jp_3.py \ third_party/python/Lib/encodings/iso2022_jp_ext.py \ third_party/python/Lib/encodings/iso2022_kr.py \ third_party/python/Lib/encodings/iso8859_1.py \ third_party/python/Lib/encodings/iso8859_10.py \ third_party/python/Lib/encodings/iso8859_11.py \ third_party/python/Lib/encodings/iso8859_13.py \ third_party/python/Lib/encodings/iso8859_14.py \ third_party/python/Lib/encodings/iso8859_15.py \ third_party/python/Lib/encodings/iso8859_16.py \ third_party/python/Lib/encodings/iso8859_2.py \ third_party/python/Lib/encodings/iso8859_3.py \ third_party/python/Lib/encodings/iso8859_4.py \ third_party/python/Lib/encodings/iso8859_5.py \ third_party/python/Lib/encodings/iso8859_6.py \ third_party/python/Lib/encodings/iso8859_7.py \ third_party/python/Lib/encodings/iso8859_8.py \ third_party/python/Lib/encodings/iso8859_9.py \ third_party/python/Lib/encodings/johab.py \ third_party/python/Lib/encodings/koi8_r.py \ third_party/python/Lib/encodings/koi8_t.py \ third_party/python/Lib/encodings/koi8_u.py \ third_party/python/Lib/encodings/kz1048.py \ third_party/python/Lib/encodings/latin_1.py \ third_party/python/Lib/encodings/mac_arabic.py \ third_party/python/Lib/encodings/mac_centeuro.py \ third_party/python/Lib/encodings/mac_croatian.py \ third_party/python/Lib/encodings/mac_cyrillic.py \ third_party/python/Lib/encodings/mac_farsi.py \ third_party/python/Lib/encodings/mac_greek.py \ third_party/python/Lib/encodings/mac_iceland.py \ third_party/python/Lib/encodings/mac_latin2.py \ third_party/python/Lib/encodings/mac_roman.py \ third_party/python/Lib/encodings/mac_romanian.py \ third_party/python/Lib/encodings/mac_turkish.py \ third_party/python/Lib/encodings/palmos.py \ third_party/python/Lib/encodings/ptcp154.py \ third_party/python/Lib/encodings/punycode.py \ third_party/python/Lib/encodings/quopri_codec.py \ third_party/python/Lib/encodings/raw_unicode_escape.py \ third_party/python/Lib/encodings/rot_13.py \ third_party/python/Lib/encodings/shift_jis.py \ third_party/python/Lib/encodings/shift_jis_2004.py \ third_party/python/Lib/encodings/shift_jisx0213.py \ third_party/python/Lib/encodings/tis_620.py \ third_party/python/Lib/encodings/undefined.py \ third_party/python/Lib/encodings/unicode_escape.py \ third_party/python/Lib/encodings/unicode_internal.py \ third_party/python/Lib/encodings/utf_16.py \ third_party/python/Lib/encodings/utf_16_be.py \ third_party/python/Lib/encodings/utf_16_le.py \ third_party/python/Lib/encodings/utf_32.py \ third_party/python/Lib/encodings/utf_32_be.py \ third_party/python/Lib/encodings/utf_32_le.py \ third_party/python/Lib/encodings/utf_7.py \ third_party/python/Lib/encodings/utf_8.py \ third_party/python/Lib/encodings/utf_8_sig.py \ third_party/python/Lib/encodings/uu_codec.py \ third_party/python/Lib/encodings/zlib_codec.py \ third_party/python/Lib/enum.py \ third_party/python/Lib/filecmp.py \ third_party/python/Lib/fileinput.py \ third_party/python/Lib/fnmatch.py \ third_party/python/Lib/formatter.py \ third_party/python/Lib/fractions.py \ third_party/python/Lib/ftplib.py \ third_party/python/Lib/functools.py \ third_party/python/Lib/genericpath.py \ third_party/python/Lib/getopt.py \ third_party/python/Lib/getpass.py \ third_party/python/Lib/gettext.py \ third_party/python/Lib/glob.py \ third_party/python/Lib/gzip.py \ third_party/python/Lib/hashlib.py \ third_party/python/Lib/heapq.py \ third_party/python/Lib/hmac.py \ third_party/python/Lib/html/__init__.py \ third_party/python/Lib/html/entities.py \ third_party/python/Lib/html/parser.py \ third_party/python/Lib/http/__init__.py \ third_party/python/Lib/http/client.py \ third_party/python/Lib/http/cookiejar.py \ third_party/python/Lib/http/cookies.py \ third_party/python/Lib/http/server.py \ third_party/python/Lib/imaplib.py \ third_party/python/Lib/imghdr.py \ third_party/python/Lib/imp.py \ third_party/python/Lib/importlib/__init__.py \ third_party/python/Lib/importlib/abc.py \ third_party/python/Lib/importlib/machinery.py \ third_party/python/Lib/importlib/util.py \ third_party/python/Lib/inspect.py \ third_party/python/Lib/io.py \ third_party/python/Lib/ipaddress.py \ third_party/python/Lib/json/__init__.py \ third_party/python/Lib/json/decoder.py \ third_party/python/Lib/json/encoder.py \ third_party/python/Lib/json/scanner.py \ third_party/python/Lib/json/tool.py \ third_party/python/Lib/keyword.py \ third_party/python/Lib/launchpy.py \ third_party/python/Lib/linecache.py \ third_party/python/Lib/locale.py \ third_party/python/Lib/logging/__init__.py \ third_party/python/Lib/logging/config.py \ third_party/python/Lib/logging/handlers.py \ third_party/python/Lib/macpath.py \ third_party/python/Lib/macurl2path.py \ third_party/python/Lib/mailbox.py \ third_party/python/Lib/mailcap.py \ third_party/python/Lib/mimetypes.py \ third_party/python/Lib/modulefinder.py \ third_party/python/Lib/multiprocessing/__init__.py \ third_party/python/Lib/multiprocessing/connection.py \ third_party/python/Lib/multiprocessing/context.py \ third_party/python/Lib/multiprocessing/dummy/__init__.py \ third_party/python/Lib/multiprocessing/dummy/connection.py \ third_party/python/Lib/multiprocessing/forkserver.py \ third_party/python/Lib/multiprocessing/heap.py \ third_party/python/Lib/multiprocessing/managers.py \ third_party/python/Lib/multiprocessing/pool.py \ third_party/python/Lib/multiprocessing/popen_fork.py \ third_party/python/Lib/multiprocessing/popen_forkserver.py \ third_party/python/Lib/multiprocessing/popen_spawn_posix.py \ third_party/python/Lib/multiprocessing/popen_spawn_win32.py \ third_party/python/Lib/multiprocessing/process.py \ third_party/python/Lib/multiprocessing/queues.py \ third_party/python/Lib/multiprocessing/reduction.py \ third_party/python/Lib/multiprocessing/resource_sharer.py \ third_party/python/Lib/multiprocessing/semaphore_tracker.py \ third_party/python/Lib/multiprocessing/spawn.py \ third_party/python/Lib/multiprocessing/synchronize.py \ third_party/python/Lib/multiprocessing/util.py \ third_party/python/Lib/netrc.py \ third_party/python/Lib/nntplib.py \ third_party/python/Lib/ntpath.py \ third_party/python/Lib/nturl2path.py \ third_party/python/Lib/numbers.py \ third_party/python/Lib/opcode.py \ third_party/python/Lib/operator.py \ third_party/python/Lib/optparse.py \ third_party/python/Lib/os.py \ third_party/python/Lib/pathlib.py \ third_party/python/Lib/pdb.py \ third_party/python/Lib/pickle.py \ third_party/python/Lib/pickletools.py \ third_party/python/Lib/pipes.py \ third_party/python/Lib/pkgutil.py \ third_party/python/Lib/platform.py \ third_party/python/Lib/plistlib.py \ third_party/python/Lib/poplib.py \ third_party/python/Lib/posixpath.py \ third_party/python/Lib/pprint.py \ third_party/python/Lib/profile.py \ third_party/python/Lib/pstats.py \ third_party/python/Lib/pty.py \ third_party/python/Lib/py_compile.py \ third_party/python/Lib/pyclbr.py \ third_party/python/Lib/pydoc.py \ third_party/python/Lib/pydoc_data/__init__.py \ third_party/python/Lib/pydoc_data/topics.py \ third_party/python/Lib/pydoc.py \ third_party/python/Lib/queue.py \ third_party/python/Lib/quopri.py \ third_party/python/Lib/random.py \ third_party/python/Lib/re.py \ third_party/python/Lib/reprlib.py \ third_party/python/Lib/runpy.py \ third_party/python/Lib/sched.py \ third_party/python/Lib/secrets.py \ third_party/python/Lib/selectors.py \ third_party/python/Lib/shelve.py \ third_party/python/Lib/shlex.py \ third_party/python/Lib/shutil.py \ third_party/python/Lib/signal.py \ third_party/python/Lib/site.py \ third_party/python/Lib/smtpd.py \ third_party/python/Lib/smtplib.py \ third_party/python/Lib/sndhdr.py \ third_party/python/Lib/socket.py \ third_party/python/Lib/socketserver.py \ third_party/python/Lib/sre_compile.py \ third_party/python/Lib/sre_constants.py \ third_party/python/Lib/sre_parse.py \ third_party/python/Lib/stat.py \ third_party/python/Lib/statistics.py \ third_party/python/Lib/string.py \ third_party/python/Lib/stringprep.py \ third_party/python/Lib/struct.py \ third_party/python/Lib/subprocess.py \ third_party/python/Lib/sunau.py \ third_party/python/Lib/symbol.py \ third_party/python/Lib/symtable.py \ third_party/python/Lib/sysconfig.py \ third_party/python/Lib/tabnanny.py \ third_party/python/Lib/tarfile.py \ third_party/python/Lib/telnetlib.py \ third_party/python/Lib/tempfile.py \ third_party/python/Lib/textwrap.py \ third_party/python/Lib/this.py \ third_party/python/Lib/threading.py \ third_party/python/Lib/timeit.py \ third_party/python/Lib/token.py \ third_party/python/Lib/tokenize.py \ third_party/python/Lib/trace.py \ third_party/python/Lib/traceback.py \ third_party/python/Lib/tracemalloc.py \ third_party/python/Lib/tty.py \ third_party/python/Lib/types.py \ third_party/python/Lib/typing.py \ third_party/python/Lib/urllib/__init__.py \ third_party/python/Lib/urllib/error.py \ third_party/python/Lib/urllib/parse.py \ third_party/python/Lib/urllib/request.py \ third_party/python/Lib/urllib/response.py \ third_party/python/Lib/urllib/robotparser.py \ third_party/python/Lib/uu.py \ third_party/python/Lib/uuid.py \ third_party/python/Lib/venv/__init__.py \ third_party/python/Lib/venv/__main__.py \ third_party/python/Lib/warnings.py \ third_party/python/Lib/wave.py \ third_party/python/Lib/weakref.py \ third_party/python/Lib/webbrowser.py \ third_party/python/Lib/wsgiref/__init__.py \ third_party/python/Lib/wsgiref/handlers.py \ third_party/python/Lib/wsgiref/headers.py \ third_party/python/Lib/wsgiref/simple_server.py \ third_party/python/Lib/wsgiref/util.py \ third_party/python/Lib/wsgiref/validate.py \ third_party/python/Lib/xdrlib.py \ third_party/python/Lib/xml/__init__.py \ third_party/python/Lib/xml/dom/NodeFilter.py \ third_party/python/Lib/xml/dom/__init__.py \ third_party/python/Lib/xml/dom/domreg.py \ third_party/python/Lib/xml/dom/expatbuilder.py \ third_party/python/Lib/xml/dom/minicompat.py \ third_party/python/Lib/xml/dom/minidom.py \ third_party/python/Lib/xml/dom/pulldom.py \ third_party/python/Lib/xml/dom/xmlbuilder.py \ third_party/python/Lib/xml/etree/ElementInclude.py \ third_party/python/Lib/xml/etree/ElementPath.py \ third_party/python/Lib/xml/etree/ElementTree.py \ third_party/python/Lib/xml/etree/__init__.py \ third_party/python/Lib/xml/etree/cElementTree.py \ third_party/python/Lib/xml/parsers/__init__.py \ third_party/python/Lib/xml/parsers/expat.py \ third_party/python/Lib/xml/sax/__init__.py \ third_party/python/Lib/xml/sax/_exceptions.py \ third_party/python/Lib/xml/sax/expatreader.py \ third_party/python/Lib/xml/sax/handler.py \ third_party/python/Lib/xml/sax/saxutils.py \ third_party/python/Lib/xml/sax/xmlreader.py \ third_party/python/Lib/xmlrpc/__init__.py \ third_party/python/Lib/xmlrpc/client.py \ third_party/python/Lib/xmlrpc/server.py \ third_party/python/Lib/zipapp.py \ third_party/python/Lib/sqlite3/__init__.py \ third_party/python/Lib/sqlite3/dump.py \ third_party/python/Lib/sqlite3/dbapi2.py \ third_party/python/Lib/zipfile.py THIRD_PARTY_PYTHON_STAGE2_A_DATA = \ third_party/python/Lib/mime.types \ third_party/python/Lib/pydoc_data/ \ third_party/python/Lib/pydoc_data/_pydoc.css THIRD_PARTY_PYTHON_STAGE2_A_DIRECTDEPS = \ DSP_CORE \ LIBC_CALLS \ LIBC_DNS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_LOG \ LIBC_MEM \ LIBC_NEXGEN32E \ LIBC_NT_KERNEL32 \ LIBC_RUNTIME \ LIBC_THREAD \ LIBC_SOCK \ LIBC_STDIO \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_SYSV_CALLS \ LIBC_TIME \ LIBC_TINYMATH \ LIBC_X \ LIBC_ZIPOS \ NET_HTTPS \ THIRD_PARTY_BZIP2 \ THIRD_PARTY_GDTOA \ THIRD_PARTY_LINENOISE \ THIRD_PARTY_MUSL \ THIRD_PARTY_PYTHON_STAGE1 \ THIRD_PARTY_MBEDTLS \ THIRD_PARTY_SQLITE3 \ THIRD_PARTY_ZLIB \ THIRD_PARTY_XED \ TOOL_ARGS THIRD_PARTY_PYTHON_STAGE2_A_DEPS = \ $(call uniq,$(foreach x,$(THIRD_PARTY_PYTHON_STAGE2_A_DIRECTDEPS),$($(x)))) o/$(MODE)/third_party/python/Python/frozen.o: \ third_party/python/Python/frozen.c \ o//third_party/python/Python/importlib.inc \ o//third_party/python/Python/importlib_external.inc ################################################################################ # TESTS THIRD_PARTY_PYTHON_PYTEST = \ $(THIRD_PARTY_PYTHON_PYTEST_A_DEPS) \ $(THIRD_PARTY_PYTHON_PYTEST_A) THIRD_PARTY_PYTHON_PYTEST_A = \ o/$(MODE)/third_party/python/python-pytest.a THIRD_PARTY_PYTHON_PYTEST_A_OBJS = \ $(THIRD_PARTY_PYTHON_PYTEST_A_PYS_OBJS) \ $(THIRD_PARTY_PYTHON_PYTEST_A_DATA_OBJS) THIRD_PARTY_PYTHON_PYTEST_A_PYS_OBJS = $(THIRD_PARTY_PYTHON_PYTEST_A_PYS:%.py=o/$(MODE)/%.o) THIRD_PARTY_PYTHON_PYTEST_A_DATA_OBJS = $(THIRD_PARTY_PYTHON_PYTEST_A_DATA:%=o/$(MODE)/%.zip.o) THIRD_PARTY_PYTHON_PYTEST_PYMAINS_OBJS = $(THIRD_PARTY_PYTHON_PYTEST_PYMAINS:%.py=o/$(MODE)/%.o) THIRD_PARTY_PYTHON_PYTEST_A_PYS = \ third_party/python/Lib/doctest.py \ third_party/python/Lib/sqlite3/test/__init__.py \ third_party/python/Lib/sqlite3/test/__init__.py \ third_party/python/Lib/sqlite3/test/dbapi.py \ third_party/python/Lib/sqlite3/test/dump.py \ third_party/python/Lib/sqlite3/test/factory.py \ third_party/python/Lib/sqlite3/test/hooks.py \ third_party/python/Lib/sqlite3/test/regression.py \ third_party/python/Lib/sqlite3/test/transactions.py \ third_party/python/Lib/sqlite3/test/types.py \ third_party/python/Lib/sqlite3/test/userfunctions.py \ third_party/python/Lib/test/__init__.py \ third_party/python/Lib/test/ann_module.py \ third_party/python/Lib/test/ann_module2.py \ third_party/python/Lib/test/ann_module3.py \ third_party/python/Lib/test/audiotests.py \ third_party/python/Lib/test/autotest.py \ third_party/python/Lib/test/bytecode_helper.py \ third_party/python/Lib/test/coding20731.py \ third_party/python/Lib/test/datetimetester.py \ third_party/python/Lib/test/dis_module.py \ third_party/python/Lib/test/doctest_aliases.py \ third_party/python/Lib/test/double_const.py \ third_party/python/Lib/test/final_a.py \ third_party/python/Lib/test/final_b.py \ third_party/python/Lib/test/fork_wait.py \ third_party/python/Lib/test/future_test1.py \ third_party/python/Lib/test/future_test2.py \ third_party/python/Lib/test/gdb_sample.py \ third_party/python/Lib/test/imp_dummy.py \ third_party/python/Lib/test/inspect_fodder.py \ third_party/python/Lib/test/inspect_fodder2.py \ third_party/python/Lib/test/leakers/__init__.py \ third_party/python/Lib/test/leakers/test_selftype.py \ third_party/python/Lib/test/libregrtest/__init__.py \ third_party/python/Lib/test/libregrtest/cmdline.py \ third_party/python/Lib/test/libregrtest/main.py \ third_party/python/Lib/test/libregrtest/refleak.py \ third_party/python/Lib/test/libregrtest/runtest.py \ third_party/python/Lib/test/libregrtest/runtest_mp.py \ third_party/python/Lib/test/libregrtest/save_env.py \ third_party/python/Lib/test/libregrtest/setup.py \ third_party/python/Lib/test/libregrtest/utils.py \ third_party/python/Lib/test/list_tests.py \ third_party/python/Lib/test/mapping_tests.py \ third_party/python/Lib/test/memory_watchdog.py \ third_party/python/Lib/test/mock_socket.py \ third_party/python/Lib/test/mod_generics_cache.py \ third_party/python/Lib/test/multibytecodec_support.py \ third_party/python/Lib/test/pickletester.py \ third_party/python/Lib/test/profilee.py \ third_party/python/Lib/test/pyclbr_input.py \ third_party/python/Lib/test/pydoc_mod.py \ third_party/python/Lib/test/pydocfodder.py \ third_party/python/Lib/test/re_tests.py \ third_party/python/Lib/test/lock_tests.py \ third_party/python/Lib/test/reperf.py \ third_party/python/Lib/test/sample_doctest.py \ third_party/python/Lib/test/sample_doctest_no_docstrings.py \ third_party/python/Lib/test/sample_doctest_no_doctests.py \ third_party/python/Lib/test/seq_tests.py \ third_party/python/Lib/test/string_tests.py \ third_party/python/Lib/test/support/__init__.py \ third_party/python/Lib/test/support/script_helper.py \ third_party/python/Lib/test/support/testresult.py \ third_party/python/Lib/test/test_dummy_thread.py \ third_party/python/Lib/test/test_email/__init__.py \ third_party/python/Lib/test/test_httpservers.py \ third_party/python/Lib/test/test_json/__init__.py \ third_party/python/Lib/test/test_math.py \ third_party/python/Lib/test/test_warnings/__init__.py \ third_party/python/Lib/test/test_warnings/data/__init__.py \ third_party/python/Lib/test/test_warnings/data/import_warning.py \ third_party/python/Lib/test/test_warnings/data/stacklevel.py \ third_party/python/Lib/test/test_xml_etree.py \ third_party/python/Lib/test/testcodec.py \ third_party/python/Lib/test/tf_inherit_check.py \ third_party/python/Lib/test/threaded_import_hangers.py \ third_party/python/Lib/test/tracedmodules/__init__.py \ third_party/python/Lib/test/tracedmodules/testmod.py \ third_party/python/Lib/test/xmltests.py \ third_party/python/Lib/unittest/__init__.py \ third_party/python/Lib/unittest/__main__.py \ third_party/python/Lib/unittest/_main.py \ third_party/python/Lib/unittest/case.py \ third_party/python/Lib/unittest/loader.py \ third_party/python/Lib/unittest/mock.py \ third_party/python/Lib/unittest/result.py \ third_party/python/Lib/unittest/runner.py \ third_party/python/Lib/unittest/signals.py \ third_party/python/Lib/unittest/suite.py \ third_party/python/Lib/unittest/test/__init__.py \ third_party/python/Lib/unittest/test/_test_warnings.py \ third_party/python/Lib/unittest/test/dummy.py \ third_party/python/Lib/unittest/test/support.py \ third_party/python/Lib/unittest/test/test_assertions.py \ third_party/python/Lib/unittest/test/test_break.py \ third_party/python/Lib/unittest/test/test_case.py \ third_party/python/Lib/unittest/test/test_functiontestcase.py \ third_party/python/Lib/unittest/test/test_loader.py \ third_party/python/Lib/unittest/test/test_program.py \ third_party/python/Lib/unittest/test/test_result.py \ third_party/python/Lib/unittest/test/test_runner.py \ third_party/python/Lib/unittest/test/test_setups.py \ third_party/python/Lib/unittest/test/test_skipping.py \ third_party/python/Lib/unittest/test/test_suite.py \ third_party/python/Lib/unittest/test/testmock/__init__.py \ third_party/python/Lib/unittest/test/testmock/support.py \ third_party/python/Lib/unittest/test/testmock/testcallable.py \ third_party/python/Lib/unittest/test/testmock/testhelpers.py \ third_party/python/Lib/unittest/test/testmock/testmagicmethods.py \ third_party/python/Lib/unittest/test/testmock/testmock.py \ third_party/python/Lib/unittest/test/testmock/testsentinel.py \ third_party/python/Lib/unittest/test/testmock/testwith.py \ third_party/python/Lib/unittest/util.py THIRD_PARTY_PYTHON_PYTEST_A_DATA = \ third_party/python/Lib/test/Python.asdl \ third_party/python/Lib/email/architecture.rst \ third_party/python/Lib/venv/scripts/common/activate \ third_party/python/Lib/venv/scripts/nt/Activate.ps1 \ third_party/python/Lib/venv/scripts/nt/activate.bat \ third_party/python/Lib/venv/scripts/nt/deactivate.bat \ third_party/python/Lib/venv/scripts/posix/activate.csh \ third_party/python/Lib/venv/scripts/posix/activate.fish \ third_party/python/Lib/test/hello.com \ third_party/python/Lib/test/xmltestdata/ \ third_party/python/Lib/test/xmltestdata/simple.xml \ third_party/python/Lib/test/xmltestdata/simple-ns.xml \ third_party/python/Lib/test/xmltestdata/expat224_utf8_bug.xml \ third_party/python/Lib/test/xmltestdata/test.xml.out \ third_party/python/Lib/test/xmltestdata/test.xml \ third_party/python/Lib/test/keycert.passwd.pem \ third_party/python/Lib/test/test_email/data/msg_44.txt \ third_party/python/Lib/test/test_email/data/PyBanner048.gif \ third_party/python/Lib/test/test_email/data/msg_40.txt \ third_party/python/Lib/test/test_email/data/msg_18.txt \ third_party/python/Lib/test/test_email/data/msg_33.txt \ third_party/python/Lib/test/test_email/data/msg_05.txt \ third_party/python/Lib/test/test_email/data/msg_09.txt \ third_party/python/Lib/test/test_email/data/msg_15.txt \ third_party/python/Lib/test/test_email/data/msg_14.txt \ third_party/python/Lib/test/test_email/data/msg_03.txt \ third_party/python/Lib/test/test_email/data/msg_32.txt \ third_party/python/Lib/test/test_email/data/msg_12.txt \ third_party/python/Lib/test/test_email/data/msg_12a.txt \ third_party/python/Lib/test/test_email/data/msg_01.txt \ third_party/python/Lib/test/test_email/data/msg_30.txt \ third_party/python/Lib/test/test_email/data/msg_36.txt \ third_party/python/Lib/test/test_email/data/msg_20.txt \ third_party/python/Lib/test/test_email/data/msg_38.txt \ third_party/python/Lib/test/test_email/data/msg_24.txt \ third_party/python/Lib/test/test_email/data/msg_31.txt \ third_party/python/Lib/test/test_email/data/msg_42.txt \ third_party/python/Lib/test/test_email/data/msg_34.txt \ third_party/python/Lib/test/test_email/data/msg_17.txt \ third_party/python/Lib/test/test_email/data/msg_07.txt \ third_party/python/Lib/test/test_email/data/msg_35.txt \ third_party/python/Lib/test/test_email/data/msg_28.txt \ third_party/python/Lib/test/test_email/data/msg_19.txt \ third_party/python/Lib/test/test_email/data/msg_02.txt \ third_party/python/Lib/test/test_email/data/msg_29.txt \ third_party/python/Lib/test/test_email/data/msg_46.txt \ third_party/python/Lib/test/test_email/data/msg_08.txt \ third_party/python/Lib/test/test_email/data/audiotest.au \ third_party/python/Lib/test/test_email/data/msg_21.txt \ third_party/python/Lib/test/test_email/data/msg_41.txt \ third_party/python/Lib/test/test_email/data/msg_23.txt \ third_party/python/Lib/test/test_email/data/msg_06.txt \ third_party/python/Lib/test/test_email/data/msg_27.txt \ third_party/python/Lib/test/test_email/data/msg_11.txt \ third_party/python/Lib/test/test_email/data/msg_16.txt \ third_party/python/Lib/test/test_email/data/msg_25.txt \ third_party/python/Lib/test/test_email/data/msg_45.txt \ third_party/python/Lib/test/test_email/data/msg_43.txt \ third_party/python/Lib/test/test_email/data/msg_22.txt \ third_party/python/Lib/test/test_email/data/msg_39.txt \ third_party/python/Lib/test/test_email/data/msg_04.txt \ third_party/python/Lib/test/test_email/data/msg_37.txt \ third_party/python/Lib/test/test_email/data/msg_13.txt \ third_party/python/Lib/test/test_email/data/msg_26.txt \ third_party/python/Lib/test/test_email/data/msg_10.txt \ third_party/python/Lib/test/sndhdrdata/ \ third_party/python/Lib/test/sndhdrdata/sndhdr.hcom \ third_party/python/Lib/test/sndhdrdata/sndhdr.wav \ third_party/python/Lib/test/sndhdrdata/sndhdr.au \ third_party/python/Lib/test/sndhdrdata/sndhdr.aifc \ third_party/python/Lib/test/sndhdrdata/sndhdr.voc \ third_party/python/Lib/test/sndhdrdata/sndhdr.aiff \ third_party/python/Lib/test/sndhdrdata/sndhdr.8svx \ third_party/python/Lib/test/sndhdrdata/sndhdr.sndt \ third_party/python/Lib/test/sndhdrdata/README \ third_party/python/Lib/test/allsans.pem \ third_party/python/Lib/test/nullcert.pem \ third_party/python/Lib/test/test_doctest.txt \ third_party/python/Lib/test/test_doctest2.txt \ third_party/python/Lib/test/test_doctest3.txt \ third_party/python/Lib/test/test_doctest4.txt \ third_party/python/Lib/test/audiodata/pluck-alaw.aifc \ third_party/python/Lib/test/audiodata/pluck-pcm32.wav \ third_party/python/Lib/test/audiodata/pluck-pcm8.aiff \ third_party/python/Lib/test/audiodata/pluck-pcm16.au \ third_party/python/Lib/test/audiodata/pluck-pcm32.au \ third_party/python/Lib/test/audiodata/pluck-pcm8.wav \ third_party/python/Lib/test/audiodata/pluck-pcm32.aiff \ third_party/python/Lib/test/audiodata/pluck-ulaw.au \ third_party/python/Lib/test/audiodata/pluck-pcm16.aiff \ third_party/python/Lib/test/audiodata/pluck-pcm24.au \ third_party/python/Lib/test/audiodata/pluck-ulaw.aifc \ third_party/python/Lib/test/audiodata/pluck-pcm16.wav \ third_party/python/Lib/test/audiodata/pluck-pcm24.aiff \ third_party/python/Lib/test/audiodata/pluck-pcm24.wav \ third_party/python/Lib/test/audiodata/pluck-pcm8.au \ third_party/python/Lib/test/imghdrdata/ \ third_party/python/Lib/test/imghdrdata/python.pgm \ third_party/python/Lib/test/imghdrdata/python.jpg \ third_party/python/Lib/test/imghdrdata/python.bmp \ third_party/python/Lib/test/imghdrdata/python.xbm \ third_party/python/Lib/test/imghdrdata/python.sgi \ third_party/python/Lib/test/imghdrdata/python.ras \ third_party/python/Lib/test/imghdrdata/python.webp \ third_party/python/Lib/test/imghdrdata/python.ppm \ third_party/python/Lib/test/imghdrdata/python.png \ third_party/python/Lib/test/imghdrdata/python.tiff \ third_party/python/Lib/test/imghdrdata/python.pbm \ third_party/python/Lib/test/imghdrdata/python.gif \ third_party/python/Lib/test/imghdrdata/python.exr \ third_party/python/Lib/test/exception_hierarchy.txt \ third_party/python/Lib/test/decimaltestdata/nexttoward.decTest \ third_party/python/Lib/test/decimaltestdata/ln.decTest \ third_party/python/Lib/test/decimaltestdata/dqMinMag.decTest \ third_party/python/Lib/test/decimaltestdata/dqCompareTotalMag.decTest \ third_party/python/Lib/test/decimaltestdata/dqSameQuantum.decTest \ third_party/python/Lib/test/decimaltestdata/dqScaleB.decTest \ third_party/python/Lib/test/decimaltestdata/testall.decTest \ third_party/python/Lib/test/decimaltestdata/dqCompareSig.decTest \ third_party/python/Lib/test/decimaltestdata/ddFMA.decTest \ third_party/python/Lib/test/decimaltestdata/decQuad.decTest \ third_party/python/Lib/test/decimaltestdata/dqClass.decTest \ third_party/python/Lib/test/decimaltestdata/nextplus.decTest \ third_party/python/Lib/test/decimaltestdata/dqNextMinus.decTest \ third_party/python/Lib/test/decimaltestdata/dqQuantize.decTest \ third_party/python/Lib/test/decimaltestdata/ddMaxMag.decTest \ third_party/python/Lib/test/decimaltestdata/ddCompareTotal.decTest \ third_party/python/Lib/test/decimaltestdata/ddCompareTotalMag.decTest \ third_party/python/Lib/test/decimaltestdata/abs.decTest \ third_party/python/Lib/test/decimaltestdata/ddAnd.decTest \ third_party/python/Lib/test/decimaltestdata/dqRemainderNear.decTest \ third_party/python/Lib/test/decimaltestdata/powersqrt.decTest \ third_party/python/Lib/test/decimaltestdata/ddReduce.decTest \ third_party/python/Lib/test/decimaltestdata/comparetotal.decTest \ third_party/python/Lib/test/decimaltestdata/ddMax.decTest \ third_party/python/Lib/test/decimaltestdata/dsEncode.decTest \ third_party/python/Lib/test/decimaltestdata/compare.decTest \ third_party/python/Lib/test/decimaltestdata/ddMin.decTest \ third_party/python/Lib/test/decimaltestdata/dqAdd.decTest \ third_party/python/Lib/test/decimaltestdata/ddCopySign.decTest \ third_party/python/Lib/test/decimaltestdata/divideint.decTest \ third_party/python/Lib/test/decimaltestdata/dqFMA.decTest \ third_party/python/Lib/test/decimaltestdata/squareroot.decTest \ third_party/python/Lib/test/decimaltestdata/dqMax.decTest \ third_party/python/Lib/test/decimaltestdata/dqRemainder.decTest \ third_party/python/Lib/test/decimaltestdata/dqRotate.decTest \ third_party/python/Lib/test/decimaltestdata/dqCopySign.decTest \ third_party/python/Lib/test/decimaltestdata/dqAbs.decTest \ third_party/python/Lib/test/decimaltestdata/max.decTest \ third_party/python/Lib/test/decimaltestdata/class.decTest \ third_party/python/Lib/test/decimaltestdata/copysign.decTest \ third_party/python/Lib/test/decimaltestdata/power.decTest \ third_party/python/Lib/test/decimaltestdata/ddMultiply.decTest \ third_party/python/Lib/test/decimaltestdata/ddDivide.decTest \ third_party/python/Lib/test/decimaltestdata/ddRemainderNear.decTest \ third_party/python/Lib/test/decimaltestdata/log10.decTest \ third_party/python/Lib/test/decimaltestdata/ddPlus.decTest \ third_party/python/Lib/test/decimaltestdata/dsBase.decTest \ third_party/python/Lib/test/decimaltestdata/remainderNear.decTest \ third_party/python/Lib/test/decimaltestdata/ddSubtract.decTest \ third_party/python/Lib/test/decimaltestdata/dqCompareTotal.decTest \ third_party/python/Lib/test/decimaltestdata/ddCompare.decTest \ third_party/python/Lib/test/decimaltestdata/ddNextToward.decTest \ third_party/python/Lib/test/decimaltestdata/extra.decTest \ third_party/python/Lib/test/decimaltestdata/dqMaxMag.decTest \ third_party/python/Lib/test/decimaltestdata/dqCopyAbs.decTest \ third_party/python/Lib/test/decimaltestdata/ddCopy.decTest \ third_party/python/Lib/test/decimaltestdata/add.decTest \ third_party/python/Lib/test/decimaltestdata/dqMinus.decTest \ third_party/python/Lib/test/decimaltestdata/ddToIntegral.decTest \ third_party/python/Lib/test/decimaltestdata/scaleb.decTest \ third_party/python/Lib/test/decimaltestdata/dqShift.decTest \ third_party/python/Lib/test/decimaltestdata/copyabs.decTest \ third_party/python/Lib/test/decimaltestdata/ddScaleB.decTest \ third_party/python/Lib/test/decimaltestdata/copynegate.decTest \ third_party/python/Lib/test/decimaltestdata/reduce.decTest \ third_party/python/Lib/test/decimaltestdata/dqEncode.decTest \ third_party/python/Lib/test/decimaltestdata/minus.decTest \ third_party/python/Lib/test/decimaltestdata/dqCopyNegate.decTest \ third_party/python/Lib/test/decimaltestdata/tointegral.decTest \ third_party/python/Lib/test/decimaltestdata/dqCopy.decTest \ third_party/python/Lib/test/decimaltestdata/dqMin.decTest \ third_party/python/Lib/test/decimaltestdata/quantize.decTest \ third_party/python/Lib/test/decimaltestdata/dqDivideInt.decTest \ third_party/python/Lib/test/decimaltestdata/shift.decTest \ third_party/python/Lib/test/decimaltestdata/clamp.decTest \ third_party/python/Lib/test/decimaltestdata/dqInvert.decTest \ third_party/python/Lib/test/decimaltestdata/exp.decTest \ third_party/python/Lib/test/decimaltestdata/dqDivide.decTest \ third_party/python/Lib/test/decimaltestdata/dqAnd.decTest \ third_party/python/Lib/test/decimaltestdata/randoms.decTest \ third_party/python/Lib/test/decimaltestdata/dqLogB.decTest \ third_party/python/Lib/test/decimaltestdata/ddOr.decTest \ third_party/python/Lib/test/decimaltestdata/comparetotmag.decTest \ third_party/python/Lib/test/decimaltestdata/or.decTest \ third_party/python/Lib/test/decimaltestdata/tointegralx.decTest \ third_party/python/Lib/test/decimaltestdata/ddLogB.decTest \ third_party/python/Lib/test/decimaltestdata/dqPlus.decTest \ third_party/python/Lib/test/decimaltestdata/rounding.decTest \ third_party/python/Lib/test/decimaltestdata/decDouble.decTest \ third_party/python/Lib/test/decimaltestdata/samequantum.decTest \ third_party/python/Lib/test/decimaltestdata/dqMultiply.decTest \ third_party/python/Lib/test/decimaltestdata/ddShift.decTest \ third_party/python/Lib/test/decimaltestdata/ddMinus.decTest \ third_party/python/Lib/test/decimaltestdata/invert.decTest \ third_party/python/Lib/test/decimaltestdata/ddSameQuantum.decTest \ third_party/python/Lib/test/decimaltestdata/dqNextToward.decTest \ third_party/python/Lib/test/decimaltestdata/minmag.decTest \ third_party/python/Lib/test/decimaltestdata/logb.decTest \ third_party/python/Lib/test/decimaltestdata/dqBase.decTest \ third_party/python/Lib/test/decimaltestdata/rotate.decTest \ third_party/python/Lib/test/decimaltestdata/subtract.decTest \ third_party/python/Lib/test/decimaltestdata/dqToIntegral.decTest \ third_party/python/Lib/test/decimaltestdata/ddBase.decTest \ third_party/python/Lib/test/decimaltestdata/ddQuantize.decTest \ third_party/python/Lib/test/decimaltestdata/and.decTest \ third_party/python/Lib/test/decimaltestdata/ddNextMinus.decTest \ third_party/python/Lib/test/decimaltestdata/inexact.decTest \ third_party/python/Lib/test/decimaltestdata/ddInvert.decTest \ third_party/python/Lib/test/decimaltestdata/ddCopyAbs.decTest \ third_party/python/Lib/test/decimaltestdata/remainder.decTest \ third_party/python/Lib/test/decimaltestdata/ddEncode.decTest \ third_party/python/Lib/test/decimaltestdata/ddXor.decTest \ third_party/python/Lib/test/decimaltestdata/ddCompareSig.decTest \ third_party/python/Lib/test/decimaltestdata/maxmag.decTest \ third_party/python/Lib/test/decimaltestdata/dqReduce.decTest \ third_party/python/Lib/test/decimaltestdata/ddCanonical.decTest \ third_party/python/Lib/test/decimaltestdata/dqNextPlus.decTest \ third_party/python/Lib/test/decimaltestdata/xor.decTest \ third_party/python/Lib/test/decimaltestdata/rescale.decTest \ third_party/python/Lib/test/decimaltestdata/ddCopyNegate.decTest \ third_party/python/Lib/test/decimaltestdata/ddRemainder.decTest \ third_party/python/Lib/test/decimaltestdata/base.decTest \ third_party/python/Lib/test/decimaltestdata/multiply.decTest \ third_party/python/Lib/test/decimaltestdata/plus.decTest \ third_party/python/Lib/test/decimaltestdata/dqCanonical.decTest \ third_party/python/Lib/test/decimaltestdata/copy.decTest \ third_party/python/Lib/test/decimaltestdata/ddRotate.decTest \ third_party/python/Lib/test/decimaltestdata/ddNextPlus.decTest \ third_party/python/Lib/test/decimaltestdata/dqSubtract.decTest \ third_party/python/Lib/test/decimaltestdata/ddAdd.decTest \ third_party/python/Lib/test/decimaltestdata/randomBound32.decTest \ third_party/python/Lib/test/decimaltestdata/dqXor.decTest \ third_party/python/Lib/test/decimaltestdata/nextminus.decTest \ third_party/python/Lib/test/decimaltestdata/dqCompare.decTest \ third_party/python/Lib/test/decimaltestdata/ddAbs.decTest \ third_party/python/Lib/test/decimaltestdata/min.decTest \ third_party/python/Lib/test/decimaltestdata/decSingle.decTest \ third_party/python/Lib/test/decimaltestdata/fma.decTest \ third_party/python/Lib/test/decimaltestdata/ddClass.decTest \ third_party/python/Lib/test/decimaltestdata/ddDivideInt.decTest \ third_party/python/Lib/test/decimaltestdata/dqOr.decTest \ third_party/python/Lib/test/decimaltestdata/ddMinMag.decTest \ third_party/python/Lib/test/decimaltestdata/divide.decTest \ third_party/python/Lib/test/decimaltestdata/ \ third_party/python/Lib/test/floating_points.txt \ third_party/python/Lib/test/badkey.pem \ third_party/python/Lib/test/revocation.crl \ third_party/python/Lib/test/recursion.tar \ third_party/python/Lib/test/tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt \ third_party/python/Lib/test/test_doctest3.txt \ third_party/python/Lib/test/keycert3.pem \ third_party/python/Lib/test/testtar.tar \ third_party/python/Lib/test/zip_cp437_header.zip \ third_party/python/Lib/test/pycakey.pem \ third_party/python/Lib/test/pycacert.pem \ third_party/python/Lib/test/ffdh3072.pem \ third_party/python/Lib/test/randv2_32.pck \ third_party/python/Lib/test/randv2_64.pck \ third_party/python/Lib/test/mailcap.txt \ third_party/python/Lib/test/test_doctest4.txt \ third_party/python/Lib/test/sgml_input.html \ third_party/python/Lib/test/test_difflib_expect.html \ third_party/python/Lib/test/math_testcases.txt \ third_party/python/Lib/test/leakers/README.txt \ third_party/python/Lib/test/nullbytecert.pem \ third_party/python/Lib/test/cfgparser.1 \ third_party/python/Lib/test/nokia.pem \ third_party/python/Lib/test/zipdir.zip \ third_party/python/Lib/test/keycert4.pem \ third_party/python/Lib/test/tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt \ third_party/python/Lib/test/test_doctest2.txt \ third_party/python/Lib/test/keycert2.pem \ third_party/python/Lib/test/capath/ceff1710.0 \ third_party/python/Lib/test/capath/99d0fa06.0 \ third_party/python/Lib/test/capath/5ed36f99.0 \ third_party/python/Lib/test/capath/b1930218.0 \ third_party/python/Lib/test/capath/6e88d7b8.0 \ third_party/python/Lib/test/capath/4e1295a3.0 \ third_party/python/Lib/test/audiotest.au \ third_party/python/Lib/test/dtracedata/ \ third_party/python/Lib/test/dtracedata/gc.d.expected \ third_party/python/Lib/test/dtracedata/gc.d \ third_party/python/Lib/test/dtracedata/line.d \ third_party/python/Lib/test/dtracedata/assert_usable.d \ third_party/python/Lib/test/dtracedata/assert_usable.stp \ third_party/python/Lib/test/dtracedata/call_stack.d \ third_party/python/Lib/test/dtracedata/call_stack.stp.expected \ third_party/python/Lib/test/dtracedata/gc.stp \ third_party/python/Lib/test/dtracedata/call_stack.stp \ third_party/python/Lib/test/dtracedata/gc.stp.expected \ third_party/python/Lib/test/dtracedata/call_stack.d.expected \ third_party/python/Lib/test/dtracedata/line.d.expected \ third_party/python/Lib/test/tokenize_tests.txt \ third_party/python/Lib/test/selfsigned_pythontestdotnet.pem \ third_party/python/Lib/test/tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt \ third_party/python/Lib/test/keycert.pem \ third_party/python/Lib/test/crashers/README \ third_party/python/Lib/test/ieee754.txt \ third_party/python/Lib/test/randv3.pck \ third_party/python/Lib/test/empty.vbs \ third_party/python/Lib/test/tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt \ third_party/python/Lib/test/Sine-1000Hz-300ms.aif \ third_party/python/Lib/test/cjkencodings/ \ third_party/python/Lib/test/cjkencodings/gbk-utf8.txt \ third_party/python/Lib/test/cjkencodings/gb2312-utf8.txt \ third_party/python/Lib/test/cjkencodings/hz-utf8.txt \ third_party/python/Lib/test/cjkencodings/euc_jisx0213-utf8.txt \ third_party/python/Lib/test/cjkencodings/euc_jisx0213.txt \ third_party/python/Lib/test/cjkencodings/johab-utf8.txt \ third_party/python/Lib/test/cjkencodings/euc_kr-utf8.txt \ third_party/python/Lib/test/cjkencodings/cp949-utf8.txt \ third_party/python/Lib/test/cjkencodings/iso2022_jp.txt \ third_party/python/Lib/test/cjkencodings/iso2022_kr-utf8.txt \ third_party/python/Lib/test/cjkencodings/johab.txt \ third_party/python/Lib/test/cjkencodings/euc_jp.txt \ third_party/python/Lib/test/cjkencodings/gb2312.txt \ third_party/python/Lib/test/cjkencodings/big5hkscs.txt \ third_party/python/Lib/test/cjkencodings/big5.txt \ third_party/python/Lib/test/cjkencodings/gbk.txt \ third_party/python/Lib/test/cjkencodings/iso2022_kr.txt \ third_party/python/Lib/test/cjkencodings/gb18030.txt \ third_party/python/Lib/test/cjkencodings/big5hkscs-utf8.txt \ third_party/python/Lib/test/cjkencodings/shift_jis.txt \ third_party/python/Lib/test/cjkencodings/cp949.txt \ third_party/python/Lib/test/cjkencodings/euc_jp-utf8.txt \ third_party/python/Lib/test/cjkencodings/hz.txt \ third_party/python/Lib/test/cjkencodings/big5-utf8.txt \ third_party/python/Lib/test/cjkencodings/gb18030-utf8.txt \ third_party/python/Lib/test/cjkencodings/shift_jisx0213.txt \ third_party/python/Lib/test/cjkencodings/shift_jis-utf8.txt \ third_party/python/Lib/test/cjkencodings/shift_jisx0213-utf8.txt \ third_party/python/Lib/test/cjkencodings/euc_kr.txt \ third_party/python/Lib/test/cjkencodings/iso2022_jp-utf8.txt \ third_party/python/Lib/test/BIG5.TXT \ third_party/python/Lib/test/BIG5HKSCS-2004.TXT \ third_party/python/Lib/test/CP932.TXT \ third_party/python/Lib/test/CP936.TXT \ third_party/python/Lib/test/CP949.TXT \ third_party/python/Lib/test/CP950.TXT \ third_party/python/Lib/test/EUC-CN.TXT \ third_party/python/Lib/test/EUC-JISX0213.TXT \ third_party/python/Lib/test/EUC-JP.TXT \ third_party/python/Lib/test/EUC-KR.TXT \ third_party/python/Lib/test/JOHAB.TXT \ third_party/python/Lib/test/SHIFTJIS.TXT \ third_party/python/Lib/test/SHIFT_JISX0213.TXT \ third_party/python/Lib/test/gb-18030-2000.ucm \ third_party/python/Lib/test/cfgparser.3 \ third_party/python/Lib/test/floating_points.txt \ third_party/python/Lib/test/formatfloat_testcases.txt \ third_party/python/Lib/test/talos-2019-0758.pem \ third_party/python/Lib/test/badcert.pem \ third_party/python/Lib/test/bad_coding.py \ third_party/python/Lib/test/bad_coding2.py \ third_party/python/Lib/test/cmath_testcases.txt \ third_party/python/Lib/test/pstats.pck \ third_party/python/Lib/test/test_importlib/namespace_pkgs/project2/parent/child/two.py \ third_party/python/Lib/test/test_importlib/namespace_pkgs/portion2/foo/two.py \ third_party/python/Lib/test/test_importlib/namespace_pkgs/project3/parent/child/three.py \ third_party/python/Lib/test/test_importlib/namespace_pkgs/portion1/foo/one.py \ third_party/python/Lib/test/test_importlib/namespace_pkgs/both_portions/foo/two.py \ third_party/python/Lib/test/test_importlib/namespace_pkgs/both_portions/foo/one.py \ third_party/python/Lib/test/test_importlib/namespace_pkgs/project1/parent/child/one.py \ third_party/python/Lib/test/test_importlib/namespace_pkgs/not_a_namespace_pkg/foo/one.py \ third_party/python/Lib/test/test_importlib/namespace_pkgs/not_a_namespace_pkg/foo/__init__.py \ third_party/python/Lib/test/test_importlib/namespace_pkgs/module_and_namespace_package/a_test.py \ third_party/python/Lib/test/dtracedata/line.py \ third_party/python/Lib/test/dtracedata/gc.py \ third_party/python/Lib/test/dtracedata/instance.py \ third_party/python/Lib/test/dtracedata/call_stack.py \ third_party/python/Lib/test/subprocessdata/qgrep.py \ third_party/python/Lib/test/subprocessdata/input_reader.py \ third_party/python/Lib/test/subprocessdata/qcat.py \ third_party/python/Lib/test/subprocessdata/sigchild_ignore.py \ third_party/python/Lib/test/subprocessdata/fd_status.py \ third_party/python/Lib/test/crashers/recursive_call.py \ third_party/python/Lib/test/crashers/gc_inspection.py \ third_party/python/Lib/test/crashers/mutation_inside_cyclegc.py \ third_party/python/Lib/test/crashers/infinite_loop_re.py \ third_party/python/Lib/test/crashers/trace_at_recursion_limit.py \ third_party/python/Lib/test/crashers/underlying_dict.py \ third_party/python/Lib/test/crashers/bogus_code_obj.py \ third_party/python/Lib/test/cfgparser.2 THIRD_PARTY_PYTHON_PYTEST_A_DIRECTDEPS = \ LIBC_NEXGEN32E \ THIRD_PARTY_PYTHON_STAGE1 \ THIRD_PARTY_PYTHON_STAGE2 ################################################################################ # TESTS THIRD_PARTY_PYTHON_PYTEST_PYMAINS = \ third_party/python/Lib/test/signalinterproctester.py \ third_party/python/Lib/test/test___future__.py \ third_party/python/Lib/test/test__locale.py \ third_party/python/Lib/test/test__opcode.py \ third_party/python/Lib/test/test_abc.py \ third_party/python/Lib/test/test_abstract_numbers.py \ third_party/python/Lib/test/test_aifc.py \ third_party/python/Lib/test/test_array.py \ third_party/python/Lib/test/test_asdl_parser.py \ third_party/python/Lib/test/test_atexit.py \ third_party/python/Lib/test/test_audioop.py \ third_party/python/Lib/test/test_augassign.py \ third_party/python/Lib/test/test_base64.py \ third_party/python/Lib/test/test_baseexception.py \ third_party/python/Lib/test/test_bigaddrspace.py \ third_party/python/Lib/test/test_bigmem.py \ third_party/python/Lib/test/test_binascii.py \ third_party/python/Lib/test/test_binhex.py \ third_party/python/Lib/test/test_binop.py \ third_party/python/Lib/test/test_bisect.py \ third_party/python/Lib/test/test_bool.py \ third_party/python/Lib/test/test_buffer.py \ third_party/python/Lib/test/test_bufio.py \ third_party/python/Lib/test/test_builtin.py \ third_party/python/Lib/test/test_bytes.py \ third_party/python/Lib/test/test_bz2.py \ third_party/python/Lib/test/test_calendar.py \ third_party/python/Lib/test/test_call.py \ third_party/python/Lib/test/test_cgi.py \ third_party/python/Lib/test/test_cgitb.py \ third_party/python/Lib/test/test_charmapcodec.py \ third_party/python/Lib/test/test_class.py \ third_party/python/Lib/test/test_cmath.py \ third_party/python/Lib/test/test_cmd.py \ third_party/python/Lib/test/test_cmd_line.py \ third_party/python/Lib/test/test_cmd_line_script.py \ third_party/python/Lib/test/test_code.py \ third_party/python/Lib/test/test_code_module.py \ third_party/python/Lib/test/test_codeccallbacks.py \ third_party/python/Lib/test/test_codecencodings_cn.py \ third_party/python/Lib/test/test_codecencodings_hk.py \ third_party/python/Lib/test/test_codecencodings_iso2022.py \ third_party/python/Lib/test/test_codecencodings_jp.py \ third_party/python/Lib/test/test_codecencodings_kr.py \ third_party/python/Lib/test/test_codecencodings_tw.py \ third_party/python/Lib/test/test_codecmaps_cn.py \ third_party/python/Lib/test/test_codecmaps_hk.py \ third_party/python/Lib/test/test_codecmaps_jp.py \ third_party/python/Lib/test/test_codecmaps_kr.py \ third_party/python/Lib/test/test_codecmaps_tw.py \ third_party/python/Lib/test/test_codecs.py \ third_party/python/Lib/test/test_codeop.py \ third_party/python/Lib/test/test_collections.py \ third_party/python/Lib/test/test_colorsys.py \ third_party/python/Lib/test/test_compare.py \ third_party/python/Lib/test/test_compile.py \ third_party/python/Lib/test/test_complex.py \ third_party/python/Lib/test/test_contains.py \ third_party/python/Lib/test/test_contextlib.py \ third_party/python/Lib/test/test_copy.py \ third_party/python/Lib/test/test_copyreg.py \ third_party/python/Lib/test/test_coroutines.py \ third_party/python/Lib/test/test_cosmo.py \ third_party/python/Lib/test/test_cprofile.py \ third_party/python/Lib/test/test_crashers.py \ third_party/python/Lib/test/test_csv.py \ third_party/python/Lib/test/test_datetime.py \ third_party/python/Lib/test/test_decimal.py \ third_party/python/Lib/test/test_decorators.py \ third_party/python/Lib/test/test_defaultdict.py \ third_party/python/Lib/test/test_deque.py \ third_party/python/Lib/test/test_descrtut.py \ third_party/python/Lib/test/test_dict.py \ third_party/python/Lib/test/test_dict_version.py \ third_party/python/Lib/test/test_dictcomps.py \ third_party/python/Lib/test/test_dictviews.py \ third_party/python/Lib/test/test_difflib.py \ third_party/python/Lib/test/test_dis.py \ third_party/python/Lib/test/test_doctest.py \ third_party/python/Lib/test/test_doctest2.py \ third_party/python/Lib/test/test_dummy_threading.py \ third_party/python/Lib/test/test_dynamic.py \ third_party/python/Lib/test/test_dynamicclassattribute.py \ third_party/python/Lib/test/test_email/test__encoded_words.py \ third_party/python/Lib/test/test_email/test__header_value_parser.py \ third_party/python/Lib/test/test_email/test_asian_codecs.py \ third_party/python/Lib/test/test_email/test_contentmanager.py \ third_party/python/Lib/test/test_email/test_defect_handling.py \ third_party/python/Lib/test/test_email/test_email.py \ third_party/python/Lib/test/test_email/test_generator.py \ third_party/python/Lib/test/test_email/test_headerregistry.py \ third_party/python/Lib/test/test_email/test_inversion.py \ third_party/python/Lib/test/test_email/test_message.py \ third_party/python/Lib/test/test_email/test_parser.py \ third_party/python/Lib/test/test_email/test_pickleable.py \ third_party/python/Lib/test/test_email/test_policy.py \ third_party/python/Lib/test/test_email/test_utils.py \ third_party/python/Lib/test/test_enum.py \ third_party/python/Lib/test/test_enumerate.py \ third_party/python/Lib/test/test_eof.py \ third_party/python/Lib/test/test_epoll.py \ third_party/python/Lib/test/test_errno.py \ third_party/python/Lib/test/test_exception_hierarchy.py \ third_party/python/Lib/test/test_exception_variations.py \ third_party/python/Lib/test/test_exceptions.py \ third_party/python/Lib/test/test_extcall.py \ third_party/python/Lib/test/test_faulthandler.py \ third_party/python/Lib/test/test_fcntl.py \ third_party/python/Lib/test/test_file.py \ third_party/python/Lib/test/test_file_eintr.py \ third_party/python/Lib/test/test_filecmp.py \ third_party/python/Lib/test/test_fileinput.py \ third_party/python/Lib/test/test_fileio.py \ third_party/python/Lib/test/test_finalization.py \ third_party/python/Lib/test/test_float.py \ third_party/python/Lib/test/test_fnmatch.py \ third_party/python/Lib/test/test_format.py \ third_party/python/Lib/test/test_fractions.py \ third_party/python/Lib/test/test_frame.py \ third_party/python/Lib/test/test_fstring.py \ third_party/python/Lib/test/test_funcattrs.py \ third_party/python/Lib/test/test_functools.py \ third_party/python/Lib/test/test_future.py \ third_party/python/Lib/test/test_future3.py \ third_party/python/Lib/test/test_future4.py \ third_party/python/Lib/test/test_future5.py \ third_party/python/Lib/test/test_gc.py \ third_party/python/Lib/test/test_generator_stop.py \ third_party/python/Lib/test/test_generators.py \ third_party/python/Lib/test/test_genericpath.py \ third_party/python/Lib/test/test_genexps.py \ third_party/python/Lib/test/test_getargs2.py \ third_party/python/Lib/test/test_getopt.py \ third_party/python/Lib/test/test_global.py \ third_party/python/Lib/test/test_grammar.py \ third_party/python/Lib/test/test_gzip.py \ third_party/python/Lib/test/test_hash.py \ third_party/python/Lib/test/test_hashlib.py \ third_party/python/Lib/test/test_heapq.py \ third_party/python/Lib/test/test_html.py \ third_party/python/Lib/test/test_htmlparser.py \ third_party/python/Lib/test/test_http_cookiejar.py \ third_party/python/Lib/test/test_http_cookies.py \ third_party/python/Lib/test/test_imghdr.py \ third_party/python/Lib/test/test_imp.py \ third_party/python/Lib/test/test_index.py \ third_party/python/Lib/test/test_int.py \ third_party/python/Lib/test/test_int_literal.py \ third_party/python/Lib/test/test_ioctl.py \ third_party/python/Lib/test/test_ipaddress.py \ third_party/python/Lib/test/test_isinstance.py \ third_party/python/Lib/test/test_iter.py \ third_party/python/Lib/test/test_iterlen.py \ third_party/python/Lib/test/test_itertools.py \ third_party/python/Lib/test/test_json/__main__.py \ third_party/python/Lib/test/test_kdf.py \ third_party/python/Lib/test/test_keywordonlyarg.py \ third_party/python/Lib/test/test_list.py \ third_party/python/Lib/test/test_listcomps.py \ third_party/python/Lib/test/test_long.py \ third_party/python/Lib/test/test_longexp.py \ third_party/python/Lib/test/test_marshal.py \ third_party/python/Lib/test/test_memoryio.py \ third_party/python/Lib/test/test_memoryview.py \ third_party/python/Lib/test/test_metaclass.py \ third_party/python/Lib/test/test_mimetypes.py \ third_party/python/Lib/test/test_minidom.py \ third_party/python/Lib/test/test_mmap.py \ third_party/python/Lib/test/test_module.py \ third_party/python/Lib/test/test_modulefinder.py \ third_party/python/Lib/test/test_multibytecodec.py \ third_party/python/Lib/test/test_numeric_tower.py \ third_party/python/Lib/test/test_opcodes.py \ third_party/python/Lib/test/test_operator.py \ third_party/python/Lib/test/test_optparse.py \ third_party/python/Lib/test/test_ordered_dict.py \ third_party/python/Lib/test/test_parser.py \ third_party/python/Lib/test/test_peepholer.py \ third_party/python/Lib/test/test_pickle.py \ third_party/python/Lib/test/test_pickletools.py \ third_party/python/Lib/test/test_pkgimport.py \ third_party/python/Lib/test/test_plistlib.py \ third_party/python/Lib/test/test_poll.py \ third_party/python/Lib/test/test_poll.py \ third_party/python/Lib/test/test_pow.py \ third_party/python/Lib/test/test_pprint.py \ third_party/python/Lib/test/test_print.py \ third_party/python/Lib/test/test_thread.py \ third_party/python/Lib/test/test_threadsignals.py \ third_party/python/Lib/test/test_profile.py \ third_party/python/Lib/test/test_property.py \ third_party/python/Lib/test/test_pstats.py \ third_party/python/Lib/test/test_pulldom.py \ third_party/python/Lib/test/test_pyexpat.py \ third_party/python/Lib/test/test_quopri.py \ third_party/python/Lib/test/test_raise.py \ third_party/python/Lib/test/test_random.py \ third_party/python/Lib/test/test_range.py \ third_party/python/Lib/test/test_re.py \ third_party/python/Lib/test/test_repl.py \ third_party/python/Lib/test/test_reprlib.py \ third_party/python/Lib/test/test_resource.py \ third_party/python/Lib/test/test_richcmp.py \ third_party/python/Lib/test/test_robotparser.py \ third_party/python/Lib/test/test_sax.py \ third_party/python/Lib/test/test_sched.py \ third_party/python/Lib/test/test_scope.py \ third_party/python/Lib/test/test_scratch.py \ third_party/python/Lib/test/test_script_helper.py \ third_party/python/Lib/test/test_secrets.py \ third_party/python/Lib/test/test_select.py \ third_party/python/Lib/test/test_selectors.py \ third_party/python/Lib/test/test_set.py \ third_party/python/Lib/test/test_setcomps.py \ third_party/python/Lib/test/test_shlex.py \ third_party/python/Lib/test/test_signal.py \ third_party/python/Lib/test/test_slice.py \ third_party/python/Lib/test/test_sndhdr.py \ third_party/python/Lib/test/test_sort.py \ third_party/python/Lib/test/test_stat.py \ third_party/python/Lib/test/test_statistics.py \ third_party/python/Lib/test/test_strftime.py \ third_party/python/Lib/test/test_string.py \ third_party/python/Lib/test/test_string_literals.py \ third_party/python/Lib/test/test_stringprep.py \ third_party/python/Lib/test/test_strptime.py \ third_party/python/Lib/test/test_strtod.py \ third_party/python/Lib/test/test_struct.py \ third_party/python/Lib/test/test_structmembers.py \ third_party/python/Lib/test/test_structseq.py \ third_party/python/Lib/test/test_subclassinit.py \ third_party/python/Lib/test/test_sunau.py \ third_party/python/Lib/test/test_super.py \ third_party/python/Lib/test/test_symbol.py \ third_party/python/Lib/test/test_symtable.py \ third_party/python/Lib/test/test_syntax.py \ third_party/python/Lib/test/test_sys_setprofile.py \ third_party/python/Lib/test/test_syslog.py \ third_party/python/Lib/test/test_tarfile.py \ third_party/python/Lib/test/test_textwrap.py \ third_party/python/Lib/test/test_time.py \ third_party/python/Lib/test/test_timeit.py \ third_party/python/Lib/test/test_timeout.py \ third_party/python/Lib/test/test_traceback.py \ third_party/python/Lib/test/test_tracemalloc.py \ third_party/python/Lib/test/test_tuple.py \ third_party/python/Lib/test/test_typechecks.py \ third_party/python/Lib/test/test_types.py \ third_party/python/Lib/test/test_typing.py \ third_party/python/Lib/test/test_unary.py \ third_party/python/Lib/test/test_unicode.py \ third_party/python/Lib/test/test_unicode_file.py \ third_party/python/Lib/test/test_unicode_identifiers.py \ third_party/python/Lib/test/test_unicodedata.py \ third_party/python/Lib/test/test_univnewlines.py \ third_party/python/Lib/test/test_unpack.py \ third_party/python/Lib/test/test_unpack_ex.py \ third_party/python/Lib/test/test_urlparse.py \ third_party/python/Lib/test/test_userdict.py \ third_party/python/Lib/test/test_userlist.py \ third_party/python/Lib/test/test_userstring.py \ third_party/python/Lib/test/test_utf8source.py \ third_party/python/Lib/test/test_uu.py \ third_party/python/Lib/test/test_uuid.py \ third_party/python/Lib/test/test_wave.py \ third_party/python/Lib/test/test_weakref.py \ third_party/python/Lib/test/test_weakset.py \ third_party/python/Lib/test/test_with.py \ third_party/python/Lib/test/test_wsgiref.py \ third_party/python/Lib/test/test_xdrlib.py \ third_party/python/Lib/test/test_xml_dom_minicompat.py \ third_party/python/Lib/test/test_xml_etree_c.py \ third_party/python/Lib/test/test_yield_from.py \ third_party/python/Lib/test/test_zipapp.py \ third_party/python/Lib/test/test_zlib.py # TODO: test_threading passing probably requires more mutexes in libc/calls/ # TODO: test_sys is potentially flaky now that we have threads THIRD_PARTY_PYTHON_PYTEST_TODOS = \ third_party/python/Lib/test/test_sys.py \ third_party/python/Lib/test/test_threading.py \ third_party/python/Lib/test/test_threading_local.py \ third_party/python/Lib/test/mp_preload.py \ third_party/python/Lib/test/outstanding_bugs.py \ third_party/python/Lib/test/pythoninfo.py \ third_party/python/Lib/test/sortperf.py \ third_party/python/Lib/test/test_asyncgen.py \ third_party/python/Lib/test/test_asynchat.py \ third_party/python/Lib/test/test_asyncore.py \ third_party/python/Lib/test/test_capi.py \ third_party/python/Lib/test/test_crypt.py \ third_party/python/Lib/test/test_devpoll.py \ third_party/python/Lib/test/test_docxmlrpc.py \ third_party/python/Lib/test/test_dtrace.py \ third_party/python/Lib/test/test_eintr.py \ third_party/python/Lib/test/test_flufl.py \ third_party/python/Lib/test/test_fork1.py \ third_party/python/Lib/test/test_ftplib.py \ third_party/python/Lib/test/test_gdb.py \ third_party/python/Lib/test/test_httplib.py \ third_party/python/Lib/test/test_imaplib.py \ third_party/python/Lib/test/test_io.py \ third_party/python/Lib/test/test_kqueue.py \ third_party/python/Lib/test/test_largefile.py \ third_party/python/Lib/test/test_linecache.py \ third_party/python/Lib/test/test_locale.py \ third_party/python/Lib/test/test_macpath.py \ third_party/python/Lib/test/test_macurl2path.py \ third_party/python/Lib/test/test_mailcap.py \ third_party/python/Lib/test/test_multiprocessing_fork.py \ third_party/python/Lib/test/test_multiprocessing_forkserver.py \ third_party/python/Lib/test/test_multiprocessing_main_handling.py \ third_party/python/Lib/test/test_multiprocessing_main_handling.py \ third_party/python/Lib/test/test_multiprocessing_main_handling.py \ third_party/python/Lib/test/test_multiprocessing_spawn.py \ third_party/python/Lib/test/test_netrc.py \ third_party/python/Lib/test/test_nis.py \ third_party/python/Lib/test/test_nntplib.py \ third_party/python/Lib/test/test_normalization.py \ third_party/python/Lib/test/test_ntpath.py \ third_party/python/Lib/test/test_openpty.py \ third_party/python/Lib/test/test_ossaudiodev.py \ third_party/python/Lib/test/test_platform.py \ third_party/python/Lib/test/test_poplib.py \ third_party/python/Lib/test/test_pty.py \ third_party/python/Lib/test/test_pyclbr.py \ third_party/python/Lib/test/test_pydoc.py \ third_party/python/Lib/test/test_queue.py \ third_party/python/Lib/test/test_readline.py \ third_party/python/Lib/test/test_regrtest.py \ third_party/python/Lib/test/test_runpy.py \ third_party/python/Lib/test/test_smtpd.py \ third_party/python/Lib/test/test_smtplib.py \ third_party/python/Lib/test/test_smtpnet.py \ third_party/python/Lib/test/test_socket.py \ third_party/python/Lib/test/test_socketserver.py \ third_party/python/Lib/test/test_spwd.py \ third_party/python/Lib/test/test_startfile.py \ third_party/python/Lib/test/test_telnetlib.py \ third_party/python/Lib/test/test_threadedtempfile.py \ third_party/python/Lib/test/test_turtle.py \ third_party/python/Lib/test/test_unittest.py \ third_party/python/Lib/test/test_urllib.py \ third_party/python/Lib/test/test_urllib2.py \ third_party/python/Lib/test/test_urllib2_localnet.py \ third_party/python/Lib/test/test_urllib2net.py \ third_party/python/Lib/test/test_urllib_response.py \ third_party/python/Lib/test/test_urllibnet.py \ third_party/python/Lib/test/test_wait3.py \ third_party/python/Lib/test/test_wait4.py \ third_party/python/Lib/test/test_webbrowser.py \ third_party/python/Lib/test/test_xmlrpc_net.py \ third_party/python/Lib/test/test_zipfile.py \ third_party/python/Lib/test/test_zipfile64.py THIRD_PARTY_PYTHON_PYTEST_PYMAINS_DIRECTDEPS = \ LIBC_NEXGEN32E \ LIBC_TESTLIB \ LIBC_LOG \ LIBC_ZIPOS \ LIBC_MEM \ LIBC_INTRIN \ LIBC_X \ LIBC_STR \ LIBC_STDIO \ LIBC_CALLS \ LIBC_RUNTIME \ THIRD_PARTY_PYTHON_STAGE1 \ THIRD_PARTY_PYTHON_STAGE2 \ THIRD_PARTY_PYTHON_PYTEST \ THIRD_PARTY_LINENOISE \ THIRD_PARTY_XED \ TOOL_ARGS THIRD_PARTY_PYTHON_PYTEST_PYMAINS_DEPS = \ $(call uniq,$(foreach x,$(THIRD_PARTY_PYTHON_PYTEST_PYMAINS_DIRECTDEPS),$($(x)))) o/$(MODE)/third_party/python/pythontester.pkg: \ $(THIRD_PARTY_PYTHON_PYTEST_PYMAINS_OBJS) \ o/$(MODE)/third_party/python/pythontester.o \ $(foreach x,$(THIRD_PARTY_PYTHON_PYTEST_PYMAINS_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/third_party/python/pythontester.com.dbg: \ o/$(MODE)/third_party/python/pythontester.pkg \ $(THIRD_PARTY_PYTHON_PYTEST_PYMAINS_DEPS) \ $(THIRD_PARTY_PYTHON_PYTEST_PYMAINS_OBJS) \ $(THIRD_PARTY_PYTHON_PYTEST_TODOS:%.py=o/$(MODE)/%.o) \ o/$(MODE)/third_party/python/pythontester.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) # if these files exist, then python will try to open them o/$(MODE)/third_party/python/Lib/test/test_robotparser.py.runs \ o/$(MODE)/third_party/python/Lib/test/test_wsgiref.py.runs: private \ .UNVEIL += \ /etc/mime.types \ /etc/httpd/mime.types \ /etc/httpd/conf/mime.types \ /etc/apache/mime.types \ /etc/apache2/mime.types \ /usr/local/etc/httpd/conf/mime.types \ /usr/local/lib/netscape/mime.types \ /usr/local/etc/httpd/conf/mime.types \ /usr/local/etc/mime.types o/$(MODE)/third_party/python/Lib/test/test_epoll.py.runs: \ private .PLEDGE = stdio rpath wpath cpath fattr proc inet o/$(MODE)/third_party/python/Lib/test/test_wsgiref.py.runs: \ private .PLEDGE = stdio rpath wpath cpath fattr proc inet o/$(MODE)/third_party/python/Lib/test/test_fcntl.py.runs: \ private .PLEDGE = stdio rpath wpath cpath fattr proc flock o/$(MODE)/third_party/python/Lib/test/test_signal.py.runs: \ private .PLEDGE = stdio rpath wpath cpath fattr proc flock inet o/$(MODE)/third_party/python/Lib/test/test_timeout.py.runs: \ private .PLEDGE = stdio rpath wpath cpath fattr proc inet o/$(MODE)/third_party/python/Lib/test/test_ioctl.py.runs: \ private .PLEDGE = stdio rpath wpath cpath fattr proc tty PYTHONTESTER = $(VM) o/$(MODE)/third_party/python/pythontester.com o/$(MODE)/third_party/python/Lib/test/test_grammar.py.runs: $(PYTHONTESTER) $(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_grammar $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_set.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_set $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_genexps.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_genexps $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_sqlite.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_sqlite $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_bz2.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_bz2 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_zlib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_zlib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_opcodes.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_opcodes $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_marshal.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_marshal $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_pow.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pow $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_binascii.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_binascii $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_binhex.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_binhex $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_capi.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_capi $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test__locale.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test__locale $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_binop.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_binop $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test___future__.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test___future__ $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test__opcode.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test__opcode $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_abc.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_abc $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_bytes.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_bytes $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_setcomps.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_setcomps $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_itertools.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_itertools $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_listcomps.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_listcomps $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_aifc.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_aifc $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_audioop.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_audioop $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_bool.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_bool $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_base64.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_base64 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_baseexception.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_baseexception $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_array.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_array $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_builtin.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_builtin $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_charmapcodec.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_charmapcodec $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecs.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecs $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codeop.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codeop $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_cgi.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_cgi $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_abstract_numbers.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_abstract_numbers $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_augassign.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_augassign $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_bigaddrspace.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_bigaddrspace $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_class.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_class $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_call.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_call $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_buffer.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_buffer $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_bufio.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_bufio $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_enum.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_enum $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_code.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_code $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_cmd.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_cmd $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_pwd.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pwd $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_cmath.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_cmath $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_defaultdict.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_defaultdict $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_decorators.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_decorators $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_copy.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_copy $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_csv.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_csv $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_difflib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_difflib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_colorsys.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_colorsys $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_compare.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_compare $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_copyreg.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_copyreg $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_collections.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_collections $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_format.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_format $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_fractions.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_fractions $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_eof.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_eof $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_fnmatch.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_fnmatch $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_frame.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_frame $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_dummy_threading.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_dummy_threading $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_dynamic.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_dynamic $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_dict.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_dict $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_wsgiref.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_wsgiref $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_wave.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_wave $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_urlparse.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_urlparse $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_userdict.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_userdict $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_userlist.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_userlist $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_userstring.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_userstring $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_utf8source.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_utf8source $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_uu.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_uu $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test__encoded_words.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test__encoded_words $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test__header_value_parser.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test__header_value_parser $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_asian_codecs.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_asian_codecs $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_contentmanager.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_contentmanager $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_defect_handling.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_defect_handling $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_email.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_email $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_generator.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_generator $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_headerregistry.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_headerregistry $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_inversion.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_inversion $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_message.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_message $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_parser.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_parser $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_pickleable.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_pickleable $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_policy.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_policy $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_email/test_utils.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_email.test_utils $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_strtod.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_strtod $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_struct.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_struct $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_structmembers.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_structmembers $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_hash.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_hash $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_heapq.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_heapq $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_operator.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_operator $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_optparse.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_optparse $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_finalization.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_finalization $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_enumerate.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_enumerate $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_errno.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_errno $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_html.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_html $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_htmlparser.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_htmlparser $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_http_cookiejar.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_http_cookiejar $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_http_cookies.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_http_cookies $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_list.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_list $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_long.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_long $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_longexp.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_longexp $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_glob.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_glob $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_global.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_global $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_ipaddress.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_ipaddress $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_isinstance.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_isinstance $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_iter.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_iter $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_json/__main__.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_json $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_tarfile.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_tarfile $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_iterlen.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_iterlen $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_stat.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_stat $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_memoryio.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_memoryio $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_memoryview.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_memoryview $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_metaclass.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_metaclass $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_mimetypes.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_mimetypes $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_kdf.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_kdf $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_cosmo.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_cosmo $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_scratch.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_scratch $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_hashlib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_hashlib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_complex.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_complex $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_funcattrs.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_funcattrs $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_functools.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_functools $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_int.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_int $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_int_literal.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_int_literal $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_bisect.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_bisect $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_pyexpat.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pyexpat $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_ioctl.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_ioctl $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_getopt.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_getopt $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_sort.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_sort $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_slice.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_slice $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_decimal.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_decimal $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_deque.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_deque $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_mmap.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_mmap $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_poll.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_poll $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_robotparser.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_robotparser $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_re.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_re $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_range.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_range $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_sax.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_sax $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_scope.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_scope $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_stringprep.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_stringprep $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_syntax.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_syntax $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_unicodedata.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_unicodedata $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_unpack.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_unpack $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_unpack_ex.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_unpack_ex $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_file.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_file $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_uuid.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_uuid $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_filecmp.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_filecmp $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_fileinput.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_fileinput $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_fileio.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_fileio $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_float.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_float $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_pickle.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pickle $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_pickletools.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pickletools $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_tuple.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_tuple $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_reprlib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_reprlib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_strftime.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_strftime $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_quopri.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_quopri $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_with.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_with $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_raise.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_raise $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_yield_from.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_yield_from $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_typechecks.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_typechecks $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_types.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_types $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_random.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_random $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_typing.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_typing $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_unary.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_unary $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_print.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_print $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_thread.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_thread $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_threading.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_threading $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_threading_local.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_threading_local $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_threadsignals.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_threadsignals $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_pprint.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pprint $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_secrets.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_secrets $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_select.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_select $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_selectors.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_selectors $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_contains.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_contains $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_super.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_super $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_unicode.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_unicode $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_unicode_file.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_unicode_file $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_unicode_identifiers.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_unicode_identifiers $(PYTESTARGS) # [jart] unsupported with landlock right now because exdev renaming # o/$(MODE)/third_party/python/Lib/test/test_unicode_file_functions.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_unicode_file_functions $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_textwrap.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_textwrap $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_pulldom.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pulldom $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_minidom.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_minidom $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_xml_dom_minicompat.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_xml_dom_minicompat $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_xml_etree_c.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_xml_etree_c $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_coroutines.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_coroutines $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_tempfile.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_tempfile $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_normalization.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_normalization $(PYTESTARGS) # [jart] unsupported with landlock right now because it needs /bin/sh # o/$(MODE)/third_party/python/Lib/test/test_os.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_os $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_logging.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_logging $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_io.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_io $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_gzip.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_gzip $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_tracemalloc.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_tracemalloc $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_configparser.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_configparser $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_flufl.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_flufl $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_keyword.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_keyword $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_keywordonlyarg.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_keywordonlyarg $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_sys.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_sys $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_cgitb.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_cgitb $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_asyncgen.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_asyncgen $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_runpy.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_runpy $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_doctest.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_doctest $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_doctest2.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_doctest2 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_calendar.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_calendar $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_asynchat.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_asynchat $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_asdl_parser.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_asdl_parser $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_atexit.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_atexit $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_dis.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_dis $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_asyncore.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_asyncore $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_epoll.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_epoll $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_cmd_line.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_cmd_line $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_cmd_line_script.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_cmd_line_script $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_code_module.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_code_module $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codeccallbacks.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codeccallbacks $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecmaps_cn.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecmaps_cn $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecmaps_jp.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecmaps_jp $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecencodings_cn.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecencodings_cn $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecencodings_hk.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecencodings_hk $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecmaps_hk.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecmaps_hk $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecmaps_kr.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecmaps_kr $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecmaps_tw.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecmaps_tw $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecencodings_iso2022.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecencodings_iso2022 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecencodings_jp.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecencodings_jp $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecencodings_kr.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecencodings_kr $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_codecencodings_tw.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_codecencodings_tw $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_compile.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_compile $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_contextlib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_contextlib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_cprofile.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_cprofile $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_crashers.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_crashers $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_crypt.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_crypt $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_datetime.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_datetime $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_descrtut.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_descrtut $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_devpoll.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_devpoll $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_dict_version.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_dict_version $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_dictcomps.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_dictcomps $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_dictviews.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_dictviews $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_dtrace.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_dtrace $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_dynamicclassattribute.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_dynamicclassattribute $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_eintr.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_eintr $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_exception_hierarchy.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_exception_hierarchy $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_xmlrpc_net.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_xmlrpc_net $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_bigmem.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_bigmem $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_exception_variations.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_exception_variations $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_exceptions.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_exceptions $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_time.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_time $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_docxmlrpc.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_docxmlrpc $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_extcall.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_extcall $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_faulthandler.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_faulthandler $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_fcntl.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_fcntl $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_file_eintr.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_file_eintr $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_fork1.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_fork1 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_fstring.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_fstring $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_ftplib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_ftplib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_future.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_future $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_future3.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_future3 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_future4.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_future4 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_future5.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_future5 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_gc.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_gc $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_gdb.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_gdb $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_generator_stop.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_generator_stop $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_generators.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_generators $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_genericpath.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_genericpath $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_getargs2.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_getargs2 $(PYTESTARGS) # [jart] incompatible with landlock because it reads /etc/passwd # o/$(MODE)/third_party/python/Lib/test/test_getpass.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_getpass $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_gettext.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_gettext $(PYTESTARGS) # [jart] incompatible with landlock because it reads /etc/passwd # o/$(MODE)/third_party/python/Lib/test/test_grp.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_grp $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_imaplib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_imaplib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_imghdr.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_imghdr $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_imp.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_imp $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_index.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_index $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_kqueue.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_kqueue $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_largefile.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_largefile $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_linecache.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_linecache $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_locale.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_locale $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_macpath.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_macpath $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_macurl2path.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_macurl2path $(PYTESTARGS) # [jart] unsupported with landlock right now because exdev renaming # o/$(MODE)/third_party/python/Lib/test/test_mailbox.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_mailbox $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_mailcap.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_mailcap $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_module.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_module $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_modulefinder.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_modulefinder $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_multibytecodec.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_multibytecodec $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_multiprocessing_fork.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_multiprocessing_fork $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_multiprocessing_forkserver.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_multiprocessing_forkserver $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_multiprocessing_main_handling.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_multiprocessing_main_handling $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_multiprocessing_spawn.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_multiprocessing_spawn $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_netrc.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_netrc $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_nis.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_nis $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_nntplib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_nntplib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_ntpath.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_ntpath $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_numeric_tower.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_numeric_tower $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_ossaudiodev.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_ossaudiodev $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_parser.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_parser $(PYTESTARGS) # [jart] unsupported with landlock right now because exdev renaming # o/$(MODE)/third_party/python/Lib/test/test_pathlib.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pathlib $(PYTESTARGS) # [jart] unsupported with landlock right now because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_pdb.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pdb $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_peepholer.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_peepholer $(PYTESTARGS) # [jart] unsupported with landlock right now because it needs /bin/sh # o/$(MODE)/third_party/python/Lib/test/test_pipes.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pipes $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_pkgimport.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pkgimport $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_platform.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_platform $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_plistlib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_plistlib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_httplib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_httplib $(PYTESTARGS) # [jart] unsupported with landlock right now because it needs /bin/sh # o/$(MODE)/third_party/python/Lib/test/test_popen.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_popen $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_poplib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_poplib $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_posix.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_posix $(PYTESTARGS) # [jart] unsupported with landlock right now because exdev renaming # o/$(MODE)/third_party/python/Lib/test/test_posixpath.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_posixpath $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_profile.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_profile $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_property.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_property $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_pstats.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pstats $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_pty.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pty $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_py_compile.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_py_compile $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_pyclbr.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pyclbr $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_pydoc.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_pydoc $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_readline.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_readline $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_regrtest.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_regrtest $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_repl.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_repl $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_resource.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_resource $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_richcmp.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_richcmp $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_sched.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_sched $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_script_helper.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_script_helper $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_shlex.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_shlex $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_shutil.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_shutil $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_signal.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_signal $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_site.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_site $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_smtpd.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_smtpd $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_smtplib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_smtplib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_smtpnet.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_smtpnet $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_sndhdr.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_sndhdr $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_socket.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_socket $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_socketserver.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_socketserver $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_spwd.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_spwd $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_startfile.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_startfile $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_statistics.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_statistics $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_string.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_string $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_string_literals.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_string_literals $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_strptime.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_strptime $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_structseq.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_structseq $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_subclassinit.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_subclassinit $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_subprocess.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_subprocess $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_sunau.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_sunau $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_support.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_support $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_symbol.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_symbol $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_symtable.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_symtable $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_sys_setprofile.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_sys_setprofile $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_syslog.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_syslog $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_telnetlib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_telnetlib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_threadedtempfile.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_threadedtempfile $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_timeit.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_timeit $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_timeout.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_timeout $(PYTESTARGS) # TODO(jart): what's wrong with this since landlock? # o/$(MODE)/third_party/python/Lib/test/test_tokenize.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_tokenize $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_trace.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_trace $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_traceback.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_traceback $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_turtle.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_turtle $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_unittest.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_unittest $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_univnewlines.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_univnewlines $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_urllib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_urllib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_urllib2.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_urllib2 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_urllib2_localnet.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_urllib2_localnet $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_urllib2net.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_urllib2net $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_urllib_response.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_urllib_response $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_urllibnet.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_urllibnet $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_wait3.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_wait3 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_wait4.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_wait4 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_webbrowser.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_webbrowser $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_xdrlib.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_xdrlib $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_weakref.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_weakref $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_weakset.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_weakset $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_zipapp.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_zipapp $(PYTESTARGS) # [jart] incompatible with landlock because it uses current directory for temp files # o/$(MODE)/third_party/python/Lib/test/test_zipimport.py.runs: $(PYTHONTESTER) # @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_zipimport $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_zipfile.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_zipfile $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_zipfile64.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_zipfile64 $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/mp_preload.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.mp_preload $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/bisect.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.bisect $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/signalinterproctester.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.signalinterproctester $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/pythoninfo.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.pythoninfo $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/datetimetester.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.datetimetester $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/outstanding_bugs.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.outstanding_bugs $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/sortperf.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.sortperf $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_openpty.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_openpty $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_queue.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_queue $(PYTESTARGS) o/$(MODE)/third_party/python/Lib/test/test_ordered_dict.py.runs: $(PYTHONTESTER) @$(COMPILE) -ACHECK -wtT$@ $(PYHARNESSARGS) $(PYTHONTESTER) -m test.test_ordered_dict $(PYTESTARGS) ################################################################################ o/$(MODE)/third_party/python/pyobj.com.dbg: \ $(THIRD_PARTY_PYTHON_STAGE1) \ o/$(MODE)/third_party/python/pyobj.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/third_party/python/pycomp.com.dbg: \ $(THIRD_PARTY_PYTHON_STAGE1) \ o/$(MODE)/third_party/python/pycomp.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/third_party/python/repl.com.dbg: \ $(THIRD_PARTY_PYTHON_STAGE2) \ o/$(MODE)/third_party/python/repl.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/third_party/python/pystone.com.dbg: \ $(THIRD_PARTY_PYTHON_STAGE2) \ o/$(MODE)/third_party/python/Lib/test/pystone.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/third_party/python/Parser/asdl_c.com.dbg: \ $(THIRD_PARTY_PYTHON_STAGE2) \ o/$(MODE)/third_party/python/Parser/asdl_c.o \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) $(THIRD_PARTY_PYTHON_STAGE2_A): \ third_party/python/Modules/ \ third_party/python/Objects/ \ $(THIRD_PARTY_PYTHON_STAGE2_A).pkg \ $(THIRD_PARTY_PYTHON_STAGE2_A_OBJS) $(THIRD_PARTY_PYTHON_PYTEST_A): \ third_party/python/Lib/test/ \ $(THIRD_PARTY_PYTHON_PYTEST_A).pkg \ $(THIRD_PARTY_PYTHON_PYTEST_A_OBJS) $(THIRD_PARTY_PYTHON_STAGE2_A).pkg: \ $(THIRD_PARTY_PYTHON_STAGE2_A_OBJS) \ $(foreach x,$(THIRD_PARTY_PYTHON_STAGE2_A_DIRECTDEPS),$($(x)_A).pkg) $(THIRD_PARTY_PYTHON_PYTEST_A).pkg: \ $(THIRD_PARTY_PYTHON_PYTEST_A_OBJS) \ $(foreach x,$(THIRD_PARTY_PYTHON_PYTEST_A_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/third_party/python/python-pymains.pkg: \ $(THIRD_PARTY_PYTHON_PYTEST_PYMAINS_OBJS) \ $(foreach x,$(THIRD_PARTY_PYTHON_PYTEST_PYMAINS_DIRECTDEPS),$($(x)_A).pkg) # includes need to be in the first 64kb, otherwise... o/$(MODE)/third_party/python/Modules/posixmodule.o: \ third_party/python/Modules/clinic/posixmodule.inc $(THIRD_PARTY_PYTHON_STAGE1_A_OBJS) \ $(THIRD_PARTY_PYTHON_STAGE2_A_OBJS): private \ OVERRIDE_CFLAGS += \ -fwrapv \ -ffunction-sections \ -fdata-sections o/$(MODE)/third_party/python/Python/ceval.o \ o/$(MODE)/third_party/python/Objects/object.o \ o/$(MODE)/third_party/python/Python/graminit.o \ o/$(MODE)/third_party/python/Objects/abstract.o: private \ OVERRIDE_CFLAGS += \ -fno-function-sections \ -fno-data-sections # use smaller relocations for indirect branches o/$(MODE)/third_party/python/Modules/_decimal/libmpdec/basearith.o \ o/$(MODE)/third_party/python/Modules/_decimal/libmpdec/mpdecimal.o \ o/$(MODE)/third_party/python/Modules/_json.o \ o/$(MODE)/third_party/python/Modules/_pickle.o \ o/$(MODE)/third_party/python/Modules/_sre.o \ o/$(MODE)/third_party/python/Modules/cjkcodecs/_codecs_jp.o \ o/$(MODE)/third_party/python/Modules/expat/xmlparse.o \ o/$(MODE)/third_party/python/Modules/expat/xmlrole.o \ o/$(MODE)/third_party/python/Modules/expat/xmltok.o \ o/$(MODE)/third_party/python/Objects/memoryobject.o \ o/$(MODE)/third_party/python/Objects/unicodeobject.o \ o/$(MODE)/third_party/python/Python/ast.o \ o/$(MODE)/third_party/python/Python/compile.o: private \ OVERRIDE_CFLAGS += \ -fpie o//third_party/python/Modules/_decimal/libmpdec/basearith.o \ o//third_party/python/Modules/_decimal/libmpdec/constants.o \ o//third_party/python/Modules/_decimal/libmpdec/context.o \ o//third_party/python/Modules/_decimal/libmpdec/convolute.o \ o//third_party/python/Modules/_decimal/libmpdec/crt.o \ o//third_party/python/Modules/_decimal/libmpdec/difradix2.o \ o//third_party/python/Modules/_decimal/libmpdec/fnt.o \ o//third_party/python/Modules/_decimal/libmpdec/fourstep.o \ o//third_party/python/Modules/_decimal/libmpdec/io.o \ o//third_party/python/Modules/_decimal/libmpdec/memory.o \ o//third_party/python/Modules/_decimal/libmpdec/mpdecimal.o \ o//third_party/python/Modules/_decimal/libmpdec/numbertheory.o \ o//third_party/python/Modules/_decimal/libmpdec/sixstep.o \ o//third_party/python/Modules/_decimal/libmpdec/transpose.o \ o//third_party/python/Modules/mathmodule.o \ o//third_party/python/Modules/hashtable.o \ o//third_party/python/Objects/abstract.o \ o//third_party/python/Objects/typeobject.o \ o//third_party/python/Objects/frameobject.o \ o//third_party/python/Objects/unicodeobject.o \ o//third_party/python/Objects/longobject.o \ o//third_party/python/Objects/dictobject.o \ o//third_party/python/Objects/obmalloc.o \ o//third_party/python/Objects/funcobject.o \ o//third_party/python/Objects/pyhash.o \ o//third_party/python/Python/ceval.o: private \ OVERRIDE_CFLAGS += \ -O2 $(THIRD_PARTY_PYTHON_STAGE1_A_OBJS) \ $(THIRD_PARTY_PYTHON_STAGE2_A_OBJS): private \ OVERRIDE_CPPFLAGS += \ -DPy_BUILD_CORE \ -DMULTIARCH='"x86_64-cosmo"' ifneq ($(MODE),dbg) $(THIRD_PARTY_PYTHON_STAGE1_A_OBJS) \ $(THIRD_PARTY_PYTHON_STAGE2_A_OBJS): private \ OVERRIDE_CPPFLAGS += \ -DNDEBUG endif o/$(MODE)/third_party/python/Python/sysmodule.o: private \ OVERRIDE_CFLAGS += \ -DABIFLAGS='"m"' # NOTE: Care must be taken that the compiler doesn't try to "optimize" # the indirect jumps by sharing them between all opcodes. Such # optimizations can be disabled on gcc by using -fno-gcse. o/$(MODE)/third_party/python/Python/ceval.o: private \ OVERRIDE_CFLAGS += \ -fno-gcse # Issue #23654: Turn off ICC's tail call optimization for the # stack_overflow generator. ICC turns the recursive tail # call into a loop. [Let's do GCC too, just to be safe.] o/$(MODE)/third_party/python/Modules/faulthandler.o: private \ OVERRIDE_CFLAGS += \ -fno-optimize-sibling-calls o/$(MODE)/third_party/python/Lib/mimetypes.o: private PYFLAGS += -Y.python/mime.types o/$(MODE)/third_party/python/Lib/test/test_baseexception.o: private PYFLAGS += -Y.python/test/exception_hierarchy.txt o/$(MODE)/third_party/python/Lib/test/test_cmath.o: private PYFLAGS += -Y.python/test/ieee754.txt o/$(MODE)/third_party/python/Lib/test/test_difflib.o: private PYFLAGS += -Y.python/test/test_difflib_expect.html o/$(MODE)/third_party/python/Lib/test/test_cosmo.o: private \ PYFLAGS += \ -Y.python/test/hello.com o/$(MODE)/third_party/python/Lib/test/test_asdl_parser.o: private \ PYFLAGS += \ -Y.python/test/Python.asdl o/$(MODE)/third_party/python/Lib/test/test_math.o: private \ PYFLAGS += \ -Y.python/test/ieee754.txt \ -Y.python/test/math_testcases.txt \ -Y.python/test/cmath_testcases.txt o/$(MODE)/third_party/python/Lib/test/audiotests.o: private \ PYFLAGS += \ -Y.python/test/audiodata/pluck-alaw.aifc \ -Y.python/test/audiodata/pluck-alaw.aifc \ -Y.python/test/audiodata/pluck-pcm16.aiff \ -Y.python/test/audiodata/pluck-pcm24.aiff \ -Y.python/test/audiodata/pluck-pcm32.aiff \ -Y.python/test/audiodata/pluck-pcm8.aiff \ -Y.python/test/audiodata/pluck-pcm8.wav \ -Y.python/test/audiodata/pluck-ulaw.aifc \ -Y.python/test/Sine-1000Hz-300ms.aif o/$(MODE)/third_party/python/Lib/test/test_wave.o: private \ PYFLAGS += \ -Y.python/test/audiodata/pluck-pcm16.wav \ -Y.python/test/audiodata/pluck-pcm24.wav \ -Y.python/test/audiodata/pluck-pcm32.wav o/$(MODE)/third_party/python/Lib/test/test_sax.o: private \ PYFLAGS += \ -Y.python/test/xmltestdata/test.xml \ -Y.python/test/xmltestdata/test.xml.out \ -Y.python/test/xmltestdata/simple.xml \ -Y.python/test/xmltestdata/simple-ns.xml o/$(MODE)/third_party/python/Lib/test/test_float.o: private \ PYFLAGS += \ -Y.python/test/floating_points.txt \ -Y.python/test/formatfloat_testcases.txt o/$(MODE)/third_party/python/Lib/test/test_tarfile.o: private \ PYFLAGS += \ -Y.python/test/zipdir.zip \ -Y.python/test/testtar.tar \ -Y.python/test/recursion.tar \ -Y.python/test/tokenize_tests.txt \ -Y.python/test/tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt \ -Y.python/test/tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt \ -Y.python/test/tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt \ -Y.python/test/tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt o/$(MODE)/third_party/python/Lib/test/test_random.o: private \ PYFLAGS += \ -Y.python/test/randv2_32.pck \ -Y.python/test/randv2_64.pck \ -Y.python/test/randv3.pck o/$(MODE)/third_party/python/Lib/test/test_pstats.o: private \ PYFLAGS += \ -Y.python/test/pstats.pck o/$(MODE)/third_party/python/Lib/test/test_sunau.o: private \ PYFLAGS += \ -Y.python/test/audiodata/pluck-alaw.aifc \ -Y.python/test/audiodata/pluck-pcm16.aiff \ -Y.python/test/audiodata/pluck-pcm16.au \ -Y.python/test/audiodata/pluck-pcm16.wav \ -Y.python/test/audiodata/pluck-pcm24.aiff \ -Y.python/test/audiodata/pluck-pcm24.au \ -Y.python/test/audiodata/pluck-pcm24.wav \ -Y.python/test/audiodata/pluck-pcm32.aiff \ -Y.python/test/audiodata/pluck-pcm32.au \ -Y.python/test/audiodata/pluck-pcm32.wav \ -Y.python/test/audiodata/pluck-pcm8.aiff \ -Y.python/test/audiodata/pluck-pcm8.au \ -Y.python/test/audiodata/pluck-pcm8.wav \ -Y.python/test/audiodata/pluck-ulaw.aifc \ -Y.python/test/audiodata/pluck-ulaw.au o/$(MODE)/third_party/python/Lib/test/test_py_compile.o: private \ PYFLAGS += \ -Y.python/test/bad_coding2.py o/$(MODE)/third_party/python/Lib/test/test_tokenize.o: private \ PYFLAGS += \ -Y.python/test/bad_coding.py \ -Y.python/test/bad_coding2.py o/$(MODE)/third_party/python/Lib/test/test_doctest.o: private \ PYFLAGS += \ -Y.python/test/test_doctest.txt \ -Y.python/test/test_doctest2.txt \ -Y.python/test/test_doctest3.txt \ -Y.python/test/test_doctest4.txt o/$(MODE)/third_party/python/Lib/test/test_imghdr.o: private \ PYFLAGS += \ -Y.python/test/imghdrdata/ \ -Y.python/test/imghdrdata/python.bmp \ -Y.python/test/imghdrdata/python.exr \ -Y.python/test/imghdrdata/python.gif \ -Y.python/test/imghdrdata/python.jpg \ -Y.python/test/imghdrdata/python.pbm \ -Y.python/test/imghdrdata/python.pgm \ -Y.python/test/imghdrdata/python.png \ -Y.python/test/imghdrdata/python.ppm \ -Y.python/test/imghdrdata/python.ras \ -Y.python/test/imghdrdata/python.sgi \ -Y.python/test/imghdrdata/python.tiff \ -Y.python/test/imghdrdata/python.webp \ -Y.python/test/imghdrdata/python.xbm o/$(MODE)/third_party/python/Lib/test/test_sndhdr.o: private \ PYFLAGS += \ -Y.python/test/sndhdrdata/ \ -Y.python/test/sndhdrdata/sndhdr.8svx \ -Y.python/test/sndhdrdata/sndhdr.aifc \ -Y.python/test/sndhdrdata/sndhdr.aiff \ -Y.python/test/sndhdrdata/sndhdr.au \ -Y.python/test/sndhdrdata/sndhdr.hcom \ -Y.python/test/sndhdrdata/sndhdr.sndt \ -Y.python/test/sndhdrdata/sndhdr.voc \ -Y.python/test/sndhdrdata/sndhdr.wav o/$(MODE)/third_party/python/Lib/test/test_email/test_email.o: private \ PYFLAGS += \ -Y.python/test/test_email/data/PyBanner048.gif \ -Y.python/test/test_email/data/audiotest.au \ -Y.python/test/test_email/data/msg_01.txt \ -Y.python/test/test_email/data/msg_02.txt \ -Y.python/test/test_email/data/msg_03.txt \ -Y.python/test/test_email/data/msg_04.txt \ -Y.python/test/test_email/data/msg_05.txt \ -Y.python/test/test_email/data/msg_06.txt \ -Y.python/test/test_email/data/msg_07.txt \ -Y.python/test/test_email/data/msg_08.txt \ -Y.python/test/test_email/data/msg_09.txt \ -Y.python/test/test_email/data/msg_10.txt \ -Y.python/test/test_email/data/msg_11.txt \ -Y.python/test/test_email/data/msg_12.txt \ -Y.python/test/test_email/data/msg_12a.txt \ -Y.python/test/test_email/data/msg_13.txt \ -Y.python/test/test_email/data/msg_14.txt \ -Y.python/test/test_email/data/msg_15.txt \ -Y.python/test/test_email/data/msg_16.txt \ -Y.python/test/test_email/data/msg_17.txt \ -Y.python/test/test_email/data/msg_18.txt \ -Y.python/test/test_email/data/msg_19.txt \ -Y.python/test/test_email/data/msg_20.txt \ -Y.python/test/test_email/data/msg_21.txt \ -Y.python/test/test_email/data/msg_22.txt \ -Y.python/test/test_email/data/msg_23.txt \ -Y.python/test/test_email/data/msg_24.txt \ -Y.python/test/test_email/data/msg_25.txt \ -Y.python/test/test_email/data/msg_26.txt \ -Y.python/test/test_email/data/msg_27.txt \ -Y.python/test/test_email/data/msg_28.txt \ -Y.python/test/test_email/data/msg_29.txt \ -Y.python/test/test_email/data/msg_30.txt \ -Y.python/test/test_email/data/msg_31.txt \ -Y.python/test/test_email/data/msg_32.txt \ -Y.python/test/test_email/data/msg_33.txt \ -Y.python/test/test_email/data/msg_34.txt \ -Y.python/test/test_email/data/msg_35.txt \ -Y.python/test/test_email/data/msg_36.txt \ -Y.python/test/test_email/data/msg_37.txt \ -Y.python/test/test_email/data/msg_38.txt \ -Y.python/test/test_email/data/msg_39.txt \ -Y.python/test/test_email/data/msg_40.txt \ -Y.python/test/test_email/data/msg_41.txt \ -Y.python/test/test_email/data/msg_42.txt \ -Y.python/test/test_email/data/msg_43.txt \ -Y.python/test/test_email/data/msg_44.txt \ -Y.python/test/test_email/data/msg_45.txt \ -Y.python/test/test_email/data/msg_46.txt o/$(MODE)/third_party/python/Lib/test/test_xml_etree_c.o \ o/$(MODE)/third_party/python/Lib/test/test_minidom.o \ o/$(MODE)/third_party/python/Lib/test/test_pulldom.o: private \ PYFLAGS += \ -Y.python/test/xmltestdata/ \ -Y.python/test/xmltestdata/simple.xml \ -Y.python/test/xmltestdata/simple-ns.xml \ -Y.python/test/xmltestdata/expat224_utf8_bug.xml \ -Y.python/test/xmltestdata/test.xml.out \ -Y.python/test/xmltestdata/test.xml o/$(MODE)/third_party/python/Lib/test/test_decimal.o: private \ PYFLAGS += \ -Y.python/test/decimaltestdata/ \ -Y.python/test/decimaltestdata/nexttoward.decTest \ -Y.python/test/decimaltestdata/ln.decTest \ -Y.python/test/decimaltestdata/dqMinMag.decTest \ -Y.python/test/decimaltestdata/dqCompareTotalMag.decTest \ -Y.python/test/decimaltestdata/dqSameQuantum.decTest \ -Y.python/test/decimaltestdata/dqScaleB.decTest \ -Y.python/test/decimaltestdata/testall.decTest \ -Y.python/test/decimaltestdata/dqCompareSig.decTest \ -Y.python/test/decimaltestdata/ddFMA.decTest \ -Y.python/test/decimaltestdata/decQuad.decTest \ -Y.python/test/decimaltestdata/dqClass.decTest \ -Y.python/test/decimaltestdata/nextplus.decTest \ -Y.python/test/decimaltestdata/dqNextMinus.decTest \ -Y.python/test/decimaltestdata/dqQuantize.decTest \ -Y.python/test/decimaltestdata/ddMaxMag.decTest \ -Y.python/test/decimaltestdata/ddCompareTotal.decTest \ -Y.python/test/decimaltestdata/ddCompareTotalMag.decTest \ -Y.python/test/decimaltestdata/abs.decTest \ -Y.python/test/decimaltestdata/ddAnd.decTest \ -Y.python/test/decimaltestdata/dqRemainderNear.decTest \ -Y.python/test/decimaltestdata/powersqrt.decTest \ -Y.python/test/decimaltestdata/ddReduce.decTest \ -Y.python/test/decimaltestdata/comparetotal.decTest \ -Y.python/test/decimaltestdata/ddMax.decTest \ -Y.python/test/decimaltestdata/dsEncode.decTest \ -Y.python/test/decimaltestdata/compare.decTest \ -Y.python/test/decimaltestdata/ddMin.decTest \ -Y.python/test/decimaltestdata/dqAdd.decTest \ -Y.python/test/decimaltestdata/ddCopySign.decTest \ -Y.python/test/decimaltestdata/divideint.decTest \ -Y.python/test/decimaltestdata/dqFMA.decTest \ -Y.python/test/decimaltestdata/squareroot.decTest \ -Y.python/test/decimaltestdata/dqMax.decTest \ -Y.python/test/decimaltestdata/dqRemainder.decTest \ -Y.python/test/decimaltestdata/dqRotate.decTest \ -Y.python/test/decimaltestdata/dqCopySign.decTest \ -Y.python/test/decimaltestdata/dqAbs.decTest \ -Y.python/test/decimaltestdata/max.decTest \ -Y.python/test/decimaltestdata/class.decTest \ -Y.python/test/decimaltestdata/copysign.decTest \ -Y.python/test/decimaltestdata/power.decTest \ -Y.python/test/decimaltestdata/ddMultiply.decTest \ -Y.python/test/decimaltestdata/ddDivide.decTest \ -Y.python/test/decimaltestdata/ddRemainderNear.decTest \ -Y.python/test/decimaltestdata/log10.decTest \ -Y.python/test/decimaltestdata/ddPlus.decTest \ -Y.python/test/decimaltestdata/dsBase.decTest \ -Y.python/test/decimaltestdata/remainderNear.decTest \ -Y.python/test/decimaltestdata/ddSubtract.decTest \ -Y.python/test/decimaltestdata/dqCompareTotal.decTest \ -Y.python/test/decimaltestdata/ddCompare.decTest \ -Y.python/test/decimaltestdata/ddNextToward.decTest \ -Y.python/test/decimaltestdata/extra.decTest \ -Y.python/test/decimaltestdata/dqMaxMag.decTest \ -Y.python/test/decimaltestdata/dqCopyAbs.decTest \ -Y.python/test/decimaltestdata/ddCopy.decTest \ -Y.python/test/decimaltestdata/add.decTest \ -Y.python/test/decimaltestdata/dqMinus.decTest \ -Y.python/test/decimaltestdata/ddToIntegral.decTest \ -Y.python/test/decimaltestdata/scaleb.decTest \ -Y.python/test/decimaltestdata/dqShift.decTest \ -Y.python/test/decimaltestdata/copyabs.decTest \ -Y.python/test/decimaltestdata/ddScaleB.decTest \ -Y.python/test/decimaltestdata/copynegate.decTest \ -Y.python/test/decimaltestdata/reduce.decTest \ -Y.python/test/decimaltestdata/dqEncode.decTest \ -Y.python/test/decimaltestdata/minus.decTest \ -Y.python/test/decimaltestdata/dqCopyNegate.decTest \ -Y.python/test/decimaltestdata/tointegral.decTest \ -Y.python/test/decimaltestdata/dqCopy.decTest \ -Y.python/test/decimaltestdata/dqMin.decTest \ -Y.python/test/decimaltestdata/quantize.decTest \ -Y.python/test/decimaltestdata/dqDivideInt.decTest \ -Y.python/test/decimaltestdata/shift.decTest \ -Y.python/test/decimaltestdata/clamp.decTest \ -Y.python/test/decimaltestdata/dqInvert.decTest \ -Y.python/test/decimaltestdata/exp.decTest \ -Y.python/test/decimaltestdata/dqDivide.decTest \ -Y.python/test/decimaltestdata/dqAnd.decTest \ -Y.python/test/decimaltestdata/randoms.decTest \ -Y.python/test/decimaltestdata/dqLogB.decTest \ -Y.python/test/decimaltestdata/ddOr.decTest \ -Y.python/test/decimaltestdata/comparetotmag.decTest \ -Y.python/test/decimaltestdata/or.decTest \ -Y.python/test/decimaltestdata/tointegralx.decTest \ -Y.python/test/decimaltestdata/ddLogB.decTest \ -Y.python/test/decimaltestdata/dqPlus.decTest \ -Y.python/test/decimaltestdata/rounding.decTest \ -Y.python/test/decimaltestdata/decDouble.decTest \ -Y.python/test/decimaltestdata/samequantum.decTest \ -Y.python/test/decimaltestdata/dqMultiply.decTest \ -Y.python/test/decimaltestdata/ddShift.decTest \ -Y.python/test/decimaltestdata/ddMinus.decTest \ -Y.python/test/decimaltestdata/invert.decTest \ -Y.python/test/decimaltestdata/ddSameQuantum.decTest \ -Y.python/test/decimaltestdata/dqNextToward.decTest \ -Y.python/test/decimaltestdata/minmag.decTest \ -Y.python/test/decimaltestdata/logb.decTest \ -Y.python/test/decimaltestdata/dqBase.decTest \ -Y.python/test/decimaltestdata/rotate.decTest \ -Y.python/test/decimaltestdata/subtract.decTest \ -Y.python/test/decimaltestdata/dqToIntegral.decTest \ -Y.python/test/decimaltestdata/ddBase.decTest \ -Y.python/test/decimaltestdata/ddQuantize.decTest \ -Y.python/test/decimaltestdata/and.decTest \ -Y.python/test/decimaltestdata/ddNextMinus.decTest \ -Y.python/test/decimaltestdata/inexact.decTest \ -Y.python/test/decimaltestdata/ddInvert.decTest \ -Y.python/test/decimaltestdata/ddCopyAbs.decTest \ -Y.python/test/decimaltestdata/remainder.decTest \ -Y.python/test/decimaltestdata/ddEncode.decTest \ -Y.python/test/decimaltestdata/ddXor.decTest \ -Y.python/test/decimaltestdata/ddCompareSig.decTest \ -Y.python/test/decimaltestdata/maxmag.decTest \ -Y.python/test/decimaltestdata/dqReduce.decTest \ -Y.python/test/decimaltestdata/ddCanonical.decTest \ -Y.python/test/decimaltestdata/dqNextPlus.decTest \ -Y.python/test/decimaltestdata/xor.decTest \ -Y.python/test/decimaltestdata/rescale.decTest \ -Y.python/test/decimaltestdata/ddCopyNegate.decTest \ -Y.python/test/decimaltestdata/ddRemainder.decTest \ -Y.python/test/decimaltestdata/base.decTest \ -Y.python/test/decimaltestdata/multiply.decTest \ -Y.python/test/decimaltestdata/plus.decTest \ -Y.python/test/decimaltestdata/dqCanonical.decTest \ -Y.python/test/decimaltestdata/copy.decTest \ -Y.python/test/decimaltestdata/ddRotate.decTest \ -Y.python/test/decimaltestdata/ddNextPlus.decTest \ -Y.python/test/decimaltestdata/dqSubtract.decTest \ -Y.python/test/decimaltestdata/ddAdd.decTest \ -Y.python/test/decimaltestdata/randomBound32.decTest \ -Y.python/test/decimaltestdata/dqXor.decTest \ -Y.python/test/decimaltestdata/nextminus.decTest \ -Y.python/test/decimaltestdata/dqCompare.decTest \ -Y.python/test/decimaltestdata/ddAbs.decTest \ -Y.python/test/decimaltestdata/min.decTest \ -Y.python/test/decimaltestdata/decSingle.decTest \ -Y.python/test/decimaltestdata/fma.decTest \ -Y.python/test/decimaltestdata/ddClass.decTest \ -Y.python/test/decimaltestdata/ddDivideInt.decTest \ -Y.python/test/decimaltestdata/dqOr.decTest \ -Y.python/test/decimaltestdata/ddMinMag.decTest \ -Y.python/test/decimaltestdata/divide.decTest o/$(MODE)/third_party/python/Lib/test/test_codecmaps_cn.o: private \ PYFLAGS += \ -Y.python/test/EUC-CN.TXT \ -Y.python/test/CP936.TXT \ -Y.python/test/gb-18030-2000.ucm o/$(MODE)/third_party/python/Lib/test/test_codecmaps_jp.o: private \ PYFLAGS += \ -Y.python/test/CP932.TXT \ -Y.python/test/EUC-JP.TXT \ -Y.python/test/SHIFTJIS.TXT \ -Y.python/test/EUC-JISX0213.TXT \ -Y.python/test/SHIFT_JISX0213.TXT o/$(MODE)/third_party/python/Lib/test/test_codecmaps_hk.o: private \ PYFLAGS += \ -Y.python/test/BIG5HKSCS-2004.TXT o/$(MODE)/third_party/python/Lib/test/test_codecmaps_kr.o: private \ PYFLAGS += \ -Y.python/test/CP949.TXT \ -Y.python/test/EUC-KR.TXT \ -Y.python/test/JOHAB.TXT o/$(MODE)/third_party/python/Lib/test/test_codecmaps_tw.o: private \ PYFLAGS += \ -Y.python/test/BIG5.TXT \ -Y.python/test/CP950.TXT o/$(MODE)/third_party/python/Lib/test/test_codecencodings_tw.o: private \ PYFLAGS += \ -Y.python/test/cjkencodings/ \ -Y.python/test/cjkencodings/big5-utf8.txt \ -Y.python/test/cjkencodings/big5.txt o/$(MODE)/third_party/python/Lib/test/test_codecencodings_kr.o: private \ PYFLAGS += \ -Y.python/test/cjkencodings/ \ -Y.python/test/cjkencodings/cp949-utf8.txt \ -Y.python/test/cjkencodings/cp949.txt \ -Y.python/test/cjkencodings/euc_kr-utf8.txt \ -Y.python/test/cjkencodings/euc_kr.txt \ -Y.python/test/cjkencodings/johab-utf8.txt \ -Y.python/test/cjkencodings/johab.txt o/$(MODE)/third_party/python/Lib/test/test_codecencodings_jp.o: private \ PYFLAGS += \ -Y.python/test/cjkencodings/ \ -Y.python/test/cjkencodings/euc_jisx0213-utf8.txt \ -Y.python/test/cjkencodings/euc_jisx0213.txt \ -Y.python/test/cjkencodings/euc_jp-utf8.txt \ -Y.python/test/cjkencodings/euc_jp.txt \ -Y.python/test/cjkencodings/euc_kr-utf8.txt \ -Y.python/test/cjkencodings/euc_kr.txt \ -Y.python/test/cjkencodings/shift_jis-utf8.txt \ -Y.python/test/cjkencodings/shift_jis.txt \ -Y.python/test/cjkencodings/shift_jisx0213-utf8.txt \ -Y.python/test/cjkencodings/shift_jisx0213.txt o/$(MODE)/third_party/python/Lib/test/test_codecencodings_iso2022.o: private \ PYFLAGS += \ -Y.python/test/cjkencodings/ \ -Y.python/test/cjkencodings/iso2022_jp-utf8.txt \ -Y.python/test/cjkencodings/iso2022_jp.txt \ -Y.python/test/cjkencodings/iso2022_kr-utf8.txt \ -Y.python/test/cjkencodings/iso2022_kr.txt o/$(MODE)/third_party/python/Lib/test/test_codecencodings_hk.o: private \ PYFLAGS += \ -Y.python/test/cjkencodings/ \ -Y.python/test/cjkencodings/big5hkscs-utf8.txt \ -Y.python/test/cjkencodings/big5hkscs.txt o/$(MODE)/third_party/python/Lib/test/test_codecencodings_cn.o: private \ PYFLAGS += \ -Y.python/test/cjkencodings/ \ -Y.python/test/cjkencodings/gb18030-utf8.txt \ -Y.python/test/cjkencodings/gb18030.txt \ -Y.python/test/cjkencodings/gb2312-utf8.txt \ -Y.python/test/cjkencodings/gb2312.txt \ -Y.python/test/cjkencodings/gbk-utf8.txt \ -Y.python/test/cjkencodings/gbk.txt \ -Y.python/test/cjkencodings/hz-utf8.txt \ -Y.python/test/cjkencodings/hz.txt $(THIRD_PARTY_PYTHON_STAGE2_A_PYS_OBJS): private PYFLAGS += -P.python -C3 $(THIRD_PARTY_PYTHON_STAGE2_A_DATA_OBJS): private ZIPOBJ_FLAGS += -P.python -C3 $(THIRD_PARTY_PYTHON_PYTEST_A_PYS_OBJS): private PYFLAGS += -P.python -C3 $(THIRD_PARTY_PYTHON_PYTEST_A_DATA_OBJS): private ZIPOBJ_FLAGS += -P.python -C3 o/$(MODE)/third_party/python/Python/ceval.o: private QUOTA = -C64 -M1024m -L300 o/$(MODE)/third_party/python/Objects/unicodeobject.o: private QUOTA += -C64 -M1024m -L300 o/$(MODE)/third_party/python/Objects/unicodeobject.o: \ third_party/python/Objects/unicodeobject.c \ third_party/python/Objects/stringlib/localeutil.inc \ third_party/python/Objects/stringlib/unicode_format.inc \ third_party/python/Objects/stringlib/asciilib.inc \ third_party/python/Objects/stringlib/codecs.inc \ third_party/python/Objects/stringlib/undef.inc \ third_party/python/Objects/stringlib/ucs1lib.inc \ third_party/python/Objects/stringlib/codecs.inc \ third_party/python/Objects/stringlib/undef.inc \ third_party/python/Objects/stringlib/ucs2lib.inc \ third_party/python/Objects/stringlib/codecs.inc \ third_party/python/Objects/stringlib/undef.inc \ third_party/python/Objects/stringlib/ucs4lib.inc \ third_party/python/Objects/stringlib/codecs.inc \ third_party/python/Objects/stringlib/undef.inc o/$(MODE)/third_party/python/Modules/_elementtree.o: \ third_party/python/Modules/_elementtree.c \ third_party/python/Modules/clinic/_elementtree.inc o/$(MODE)/third_party/python/Modules/_io/bufferedio.o: \ third_party/python/Modules/_io/bufferedio.c \ third_party/python/Modules/_io/clinic/bufferedio.inc o/$(MODE)/third_party/python/Modules/_io/textio.o: \ third_party/python/Modules/_io/textio.c \ third_party/python/Modules/_io/clinic/textio.inc o/$(MODE)/third_party/python/Modules/_sre.o: \ third_party/python/Modules/_sre.c \ third_party/python/Modules/clinic/_sre.inc o/$(MODE)/third_party/python/Parser/asdl_c.o: private PYFLAGS += -m $(THIRD_PARTY_PYTHON_PYTEST_PYMAINS_OBJS): private PYFLAGS += -t -P.python -C3 $(THIRD_PARTY_PYTHON_PYTEST_TODOS:%.py=o/$(MODE)/%.o): private PYFLAGS += -t -P.python -C3 o/$(MODE)/third_party/python/Lib/test/pystone.o: private PYFLAGS += -m -O2 -P.python -C4 o/$(MODE)/third_party/python/Lib/test/test_long.py.runs: private QUOTA = -C64 -L180 o/$(MODE)/third_party/python/Lib/test/test_hash.py.runs: private QUOTA = -C64 o/$(MODE)/third_party/python/Lib/test/test_exceptions.py.runs: private QUOTA = -C64 o/$(MODE)/third_party/python/Lib/test/test_tuple.py.runs: private QUOTA = -M512m o/$(MODE)/third_party/python/Lib/test/test_decimal.py.runs: private QUOTA = -M512m -C64 -L300 o/$(MODE)/third_party/python/Lib/test/test_longexp.py.runs: private QUOTA = -M1024m o/$(MODE)/third_party/python/Lib/test/test_unicode.py.runs: private QUOTA = -M1400m -L300 o/$(MODE)/third_party/python/Lib/test/test_unicodedata.py.runs: private QUOTA = -C64 -L300 o/$(MODE)/third_party/python/Lib/test/test_logging.py.runs: private QUOTA = -M512m o/$(MODE)/third_party/python/Lib/test/test_itertools.py.runs: private QUOTA = -M1024m o/$(MODE)/third_party/python/Lib/test/test_tarfile.py.runs: private QUOTA = -L300 -C64 o/$(MODE)/third_party/python/Lib/test/test_sqlite.py.runs: private QUOTA = -L120 o/$(MODE)/third_party/python/Lib/test/test_gzip.py.runs: private QUOTA = -L120 o/$(MODE)/third_party/python/Lib/test/test_logging.py.runs: private QUOTA = -M512m o/$(MODE)/third_party/python/Lib/test/test_resource.py.runs: private QUOTA = -C1000000 o/$(MODE)/third_party/python/Lib/test/test_email/test_email.py.runs: private QUOTA = -C32 -M1024m o/$(MODE)/third_party/python/Lib/test/test_selectors.py.runs: private QUOTA = -L180 o/$(MODE)/third_party/python/Lib/test/test_trace.py.runs: private QUOTA = -L300 o/$(MODE)/third_party/python/Lib/test/test_multibytecodec.py.runs: private QUOTA = -L300 o/$(MODE)/third_party/python/Lib/test/test_bz2.py.runs: private QUOTA = -L300 o/$(MODE)/third_party/python/Lib/test/test_bytes.py.runs: private QUOTA = -L300 o/$(MODE)/third_party/python/Lib/test/test_urlparse.py.runs: private QUOTA = -L300 o/$(MODE)/third_party/python/Modules/_decimal/libmpdec/mpdecimal.o: private QUOTA = -L180 o/$(MODE)/third_party/python/Modules/_sre.o: private QUOTA = -L180 o/dbg/third_party/python/Lib/test/test_set.py.runs: private QUOTA = -L300 THIRD_PARTY_PYTHON_LIBS = \ $(foreach x,$(THIRD_PARTY_PYTHON_ARTIFACTS),$($(x))) THIRD_PARTY_PYTHON_OBJS = \ $(foreach x,$(THIRD_PARTY_PYTHON_ARTIFACTS),$($(x)_OBJS)) \ o/$(MODE)/third_party/python/pyobj.o \ o/$(MODE)/third_party/python/pycomp.o THIRD_PARTY_PYTHON_SRCS = \ $(foreach x,$(THIRD_PARTY_PYTHON_ARTIFACTS),$($(x)_SRCS)) \ third_party/python/pyobj.c \ third_party/python/pycomp.c \ third_party/python/repl.c \ third_party/python/pythontester.c ################################################################################ # PYTHON.COM THIRD_PARTY_PYTHON_PYTHON_SRCS = third_party/python/python.c THIRD_PARTY_PYTHON_PYTHON_OBJS = o/$(MODE)/third_party/python/python.o THIRD_PARTY_PYTHON_PYTHON_COMS = o/$(MODE)/third_party/python/python.com THIRD_PARTY_PYTHON_PYTHON_BINS = $(THIRD_PARTY_PYTHON_PYTHON_COMS) $(THIRD_PARTY_PYTHON_PYTHON_COMS:%=%.dbg) THIRD_PARTY_PYTHON_PYTHON_DEPS = $(call uniq,$(foreach x,$(THIRD_PARTY_PYTHON_PYTHON_DIRECTDEPS),$($(x)))) THIRD_PARTY_PYTHON_PYTHON_DIRECTDEPS = \ LIBC_CALLS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_STDIO \ LIBC_MEM \ LIBC_STR \ LIBC_STUBS \ LIBC_LOG \ LIBC_SYSV \ LIBC_X \ LIBC_ZIPOS \ THIRD_PARTY_GETOPT \ THIRD_PARTY_LINENOISE \ THIRD_PARTY_PYTHON_STAGE1 \ THIRD_PARTY_PYTHON_STAGE2 \ THIRD_PARTY_PYTHON_PYTEST \ THIRD_PARTY_XED \ TOOL_ARGS o/$(MODE)/third_party/python/python.pkg: \ $(THIRD_PARTY_PYTHON_PYTHON_OBJS) \ $(foreach x,$(THIRD_PARTY_PYTHON_PYTHON_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/third_party/python/python.com.dbg: \ o/$(MODE)/third_party/python/python.pkg \ $(THIRD_PARTY_PYTHON_PYTHON_DEPS) \ $(THIRD_PARTY_PYTHON_PYTHON_OBJS) \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) o/$(MODE)/third_party/python/python.com: \ o/$(MODE)/third_party/python/python.com.dbg \ o/$(MODE)/third_party/zip/zip.com \ o/$(MODE)/tool/build/symtab.com \ $(VM) @$(MAKE_OBJCOPY) @$(MAKE_SYMTAB_CREATE) @$(MAKE_SYMTAB_ZIP) ################################################################################ # FREEZE.COM THIRD_PARTY_PYTHON_FREEZE_SRCS = third_party/python/freeze.c THIRD_PARTY_PYTHON_FREEZE_OBJS = o/$(MODE)/third_party/python/freeze.o THIRD_PARTY_PYTHON_FREEZE_COMS = o/$(MODE)/third_party/python/freeze.com THIRD_PARTY_PYTHON_FREEZE_BINS = $(THIRD_PARTY_PYTHON_FREEZE_COMS) $(THIRD_PARTY_PYTHON_FREEZE_COMS:%=%.dbg) THIRD_PARTY_PYTHON_FREEZE_DEPS = $(call uniq,$(foreach x,$(THIRD_PARTY_PYTHON_FREEZE_DIRECTDEPS),$($(x)))) THIRD_PARTY_PYTHON_FREEZE_DIRECTDEPS = \ LIBC_CALLS \ LIBC_FMT \ LIBC_INTRIN \ LIBC_NEXGEN32E \ LIBC_RUNTIME \ LIBC_STDIO \ LIBC_MEM \ LIBC_STR \ LIBC_STUBS \ LIBC_SYSV \ LIBC_X \ THIRD_PARTY_GETOPT \ THIRD_PARTY_XED \ THIRD_PARTY_PYTHON_STAGE1 o/$(MODE)/third_party/python/freeze.pkg: \ $(THIRD_PARTY_PYTHON_FREEZE_OBJS) \ $(foreach x,$(THIRD_PARTY_PYTHON_FREEZE_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/third_party/python/freeze.com.dbg: \ o/$(MODE)/third_party/python/freeze.pkg \ $(THIRD_PARTY_PYTHON_FREEZE_DEPS) \ $(THIRD_PARTY_PYTHON_FREEZE_OBJS) \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) .PRECIOUS: o/$(MODE)/third_party/python/chibicc.inc o/$(MODE)/third_party/python/chibicc.inc: \ third_party/python/chibicc.inc \ libc/assert.h \ libc/intrin/likely.h \ libc/calls/struct/stat.h \ libc/calls/struct/timespec.h \ libc/dce.h \ libc/errno.h \ libc/fmt/fmts.h \ libc/fmt/pflink.h \ libc/integral/c.inc \ libc/integral/lp64arg.inc \ libc/integral/normalize.inc \ libc/limits.h \ libc/math.h \ libc/mem/mem.h \ libc/nexgen32e/kcpuids.h \ libc/runtime/runtime.h \ libc/runtime/symbolic.h \ libc/stdio/stdio.h \ libc/str/str.h \ libc/str/unicode.h \ third_party/python/Include/Python.h \ third_party/python/Include/abstract.h \ third_party/python/Include/bltinmodule.h \ third_party/python/Include/boolobject.h \ third_party/python/Include/bytearrayobject.h \ third_party/python/Include/bytesobject.h \ third_party/python/Include/cellobject.h \ third_party/python/Include/ceval.h \ third_party/python/Include/classobject.h \ third_party/python/Include/code.h \ third_party/python/Include/codecs.h \ third_party/python/Include/compile.h \ third_party/python/Include/complexobject.h \ third_party/python/Include/descrobject.h \ third_party/python/Include/dictobject.h \ third_party/python/Include/dtoa.h \ third_party/python/Include/dynamic_annotations.h \ third_party/python/Include/enumobject.h \ third_party/python/Include/eval.h \ third_party/python/Include/fileobject.h \ third_party/python/Include/fileutils.h \ third_party/python/Include/floatobject.h \ third_party/python/Include/funcobject.h \ third_party/python/Include/genobject.h \ third_party/python/Include/import.h \ third_party/python/Include/intrcheck.h \ third_party/python/Include/iterobject.h \ third_party/python/Include/listobject.h \ third_party/python/Include/longintrepr.h \ third_party/python/Include/longobject.h \ third_party/python/Include/memoryobject.h \ third_party/python/Include/methodobject.h \ third_party/python/Include/modsupport.h \ third_party/python/Include/moduleobject.h \ third_party/python/Include/namespaceobject.h \ third_party/python/Include/object.h \ third_party/python/Include/objimpl.h \ third_party/python/Include/odictobject.h \ third_party/python/Include/op.h \ third_party/python/Include/osmodule.h \ third_party/python/Include/patchlevel.h \ third_party/python/Include/pyarena.h \ third_party/python/Include/pyatomic.h \ third_party/python/Include/pycapsule.h \ third_party/python/Include/pyctype.h \ third_party/python/Include/pydebug.h \ third_party/python/Include/pyerrors.h \ third_party/python/Include/pyfpe.h \ third_party/python/Include/pyhash.h \ third_party/python/Include/pylifecycle.h \ third_party/python/Include/pymacro.h \ third_party/python/Include/pymath.h \ third_party/python/Include/pymem.h \ third_party/python/Include/pyport.h \ third_party/python/Include/pystate.h \ third_party/python/Include/pystrcmp.h \ third_party/python/Include/pystrtod.h \ third_party/python/Include/pythonrun.h \ third_party/python/Include/pytime.h \ third_party/python/Include/rangeobject.h \ third_party/python/Include/setobject.h \ third_party/python/Include/sliceobject.h \ third_party/python/Include/structseq.h \ third_party/python/Include/sysmodule.h \ third_party/python/Include/traceback.h \ third_party/python/Include/tupleobject.h \ third_party/python/Include/typeslots.h \ third_party/python/Include/unicodeobject.h \ third_party/python/Include/warnings.h \ third_party/python/Include/weakrefobject.h \ third_party/python/pyconfig.h @$(COMPILE) -wACHECK.h $(COMPILE.c) -xc -E -P -fdirectives-only -dD -D__chibicc__ -o $@ $< ################################################################################ # HELLO.COM THIRD_PARTY_PYTHON_HELLO_SRCS = third_party/python/hello.c THIRD_PARTY_PYTHON_HELLO_OBJS = o/$(MODE)/third_party/python/hello.o THIRD_PARTY_PYTHON_HELLO_COMS = o/$(MODE)/third_party/python/hello.com THIRD_PARTY_PYTHON_HELLO_BINS = $(THIRD_PARTY_PYTHON_HELLO_COMS) $(THIRD_PARTY_PYTHON_HELLO_COMS:%=%.dbg) THIRD_PARTY_PYTHON_HELLO_DEPS = $(call uniq,$(foreach x,$(THIRD_PARTY_PYTHON_HELLO_DIRECTDEPS),$($(x)))) THIRD_PARTY_PYTHON_HELLO_DIRECTDEPS = \ THIRD_PARTY_PYTHON_STAGE1 \ THIRD_PARTY_PYTHON_STAGE2 o/$(MODE)/third_party/python/hello.pkg: \ $(THIRD_PARTY_PYTHON_HELLO_OBJS) \ $(foreach x,$(THIRD_PARTY_PYTHON_HELLO_DIRECTDEPS),$($(x)_A).pkg) o/$(MODE)/third_party/python/hello.com.dbg: \ o/$(MODE)/third_party/python/hello.pkg \ $(THIRD_PARTY_PYTHON_HELLO_DEPS) \ $(THIRD_PARTY_PYTHON_HELLO_OBJS) \ $(CRT) \ $(APE_NO_MODIFY_SELF) @$(APELINK) $(THIRD_PARTY_PYTHON_HELLO_OBJS): private PYFLAGS += -C2 -m # this directory entry is at the tip of the tree # therefore building it requires special care o/$(MODE)/third_party/python/Lib/.zip.o: third_party/python/.python @$(COMPILE) -wAZIPOBJ $(ZIPOBJ) -b$(IMAGE_BASE_VIRTUAL) -C2 $(OUTPUT_OPTION) third_party/python/.python # these need to be explictly defined because landlock make won't sandbox # prerequisites with a trailing slash. o/$(MODE)/third_party/python/Lib/pydoc_data/.zip.o: \ third_party/python/Lib/pydoc_data o/$(MODE)/third_party/python/Lib/test/xmltestdata/.zip.o: \ third_party/python/Lib/test/xmltestdata o/$(MODE)/third_party/python/Lib/test/sndhdrdata/.zip.o: \ third_party/python/Lib/test/sndhdrdata o/$(MODE)/third_party/python/Lib/test/imghdrdata/.zip.o: \ third_party/python/Lib/test/imghdrdata o/$(MODE)/third_party/python/Lib/test/decimaltestdata/.zip.o: \ third_party/python/Lib/test/decimaltestdata o/$(MODE)/third_party/python/Lib/test/dtracedata/.zip.o: \ third_party/python/Lib/test/dtracedata o/$(MODE)/third_party/python/Lib/test/cjkencodings/.zip.o: \ third_party/python/Lib/test/cjkencodings o/$(MODE)/third_party/python/Modules/.zip.o: \ third_party/python/Modules o/$(MODE)/third_party/python/Objects/.zip.o: \ third_party/python/Objects o/$(MODE)/third_party/python/Lib/test/.zip.o: \ third_party/python/Lib/test ################################################################################ .PHONY: o/$(MODE)/third_party/python o/$(MODE)/third_party/python: \ $(THIRD_PARTY_PYTHON_BINS) \ $(THIRD_PARTY_PYTHON_CHECKS)
215,542
4,226
jart/cosmopolitan
false
cosmopolitan/third_party/python/pyconfig.h
#ifndef Py_PYCONFIG_H #define Py_PYCONFIG_H #include "libc/calls/calls.h" #include "libc/dce.h" #include "libc/str/str.h" #define STDC_HEADERS 1 #define HAVE_LONG_DOUBLE 1 #define HAVE_GCC_UINT128_T 1 #define HAVE_STDARG_PROTOTYPES 1 #define HAVE_BUILTIN_ATOMIC 1 #define HAVE_COMPUTED_GOTOS 1 #define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 1 #ifdef __x86_64__ #define HAVE_GCC_ASM_FOR_X64 1 #define HAVE_GCC_ASM_FOR_X87 1 #endif #define HAVE_ACOSH 1 #define HAVE_ASINH 1 #define HAVE_ATANH 1 #define HAVE_COPYSIGN 1 #define HAVE_FINITE 1 #define HAVE_LGAMMA 1 #define HAVE_TGAMMA 1 #define HAVE_HYPOT 1 #define HAVE_ROUND 1 #define HAVE_LOG1P 1 #define HAVE_LOG2 1 #define HAVE_DECL_ISFINITE 1 #define HAVE_DECL_ISINF 1 #define HAVE_DECL_ISNAN 1 /* #undef HAVE_GAMMA */ #define HAVE_ACCEPT4 1 #define HAVE_ADDRINFO 1 #define HAVE_ALARM 1 #define HAVE_CLOCK 1 /* #undef HAVE_CHFLAGS */ #define HAVE_WORKING_TZSET 1 #define HAVE_STRUCT_TM_TM_ZONE 1 #define HAVE_TM_ZONE 1 /* deprecated */ #define HAVE_DECL_TZNAME 1 /* #undef HAVE_ALTZONE */ /* #undef GETTIMEOFDAY_NO_TZ */ #define HAVE_CLOCK_GETRES 1 #define HAVE_CLOCK_GETTIME 1 #define HAVE_CLOCK_SETTIME 1 /* Define to 1 if you have the `confstr' function. */ /* #undef HAVE_CONFSTR */ /* Define to 1 if you have the `ctermid' function. */ #define HAVE_CTERMID 1 /* Define if you have the 'ctermid_r' function. */ /* #undef HAVE_CTERMID_R */ /* Define if you have the 'filter' function. */ #define HAVE_CURSES_FILTER 1 /* Define if you have the 'has_key' function. */ #define HAVE_CURSES_HAS_KEY 1 /* Define if you have the 'immedok' function. */ #define HAVE_CURSES_IMMEDOK 1 /* Define if you have the 'is_pad' function or macro. */ #define HAVE_CURSES_IS_PAD 1 /* Define if you have the 'is_term_resized' function. */ #define HAVE_CURSES_IS_TERM_RESIZED 1 /* Define if you have the 'resizeterm' function. */ #define HAVE_CURSES_RESIZETERM 1 /* Define if you have the 'resize_term' function. */ #define HAVE_CURSES_RESIZE_TERM 1 /* Define if you have the 'syncok' function. */ #define HAVE_CURSES_SYNCOK 1 /* Define if you have the 'typeahead' function. */ #define HAVE_CURSES_TYPEAHEAD 1 /* Define if you have the 'use_env' function. */ #define HAVE_CURSES_USE_ENV 1 /* Define if you have the 'wchgat' function. */ #define HAVE_CURSES_WCHGAT 1 #define HAVE_DLOPEN 1 #define HAVE_DYNAMIC_LOADING 1 #define HAVE_DECL_RTLD_DEEPBIND 0 #define HAVE_DECL_RTLD_GLOBAL 1 #define HAVE_DECL_RTLD_LAZY 1 #define HAVE_DECL_RTLD_LOCAL 1 #define HAVE_DECL_RTLD_NODELETE 0 #define HAVE_DECL_RTLD_NOLOAD 0 #define HAVE_DECL_RTLD_NOW 1 #define HAVE_GETSID 1 #define HAVE_GETEUID 1 #define HAVE_GETTIMEOFDAY 1 #define HAVE_GETUID 1 #define HAVE_GETNAMEINFO 1 #define HAVE_GETPAGESIZE 1 #define HAVE_GETPEERNAME 1 #define HAVE_GETPGID 1 #define HAVE_GETPGRP 1 #define HAVE_GETPID 1 #define HAVE_GETGID 1 #define HAVE_GETPRIORITY 1 #define HAVE_GETPWENT 1 #define HAVE_GETRANDOM 1 #define HAVE_GETITIMER 1 #define HAVE_CHOWN 1 #define HAVE_CHROOT 1 #define HAVE_DIRENT_D_TYPE 1 #define HAVE_DUP2 1 #define HAVE_DUP3 1 #define HAVE_EPOLL 1 #define HAVE_EPOLL_CREATE1 1 #define HAVE_ERF 1 #define HAVE_ERFC 1 #define HAVE_EXECV 1 #define HAVE_EXPM1 1 #define HAVE_FACCESSAT 1 #define HAVE_FCHDIR 1 #define HAVE_FCHMOD 1 #define HAVE_FCHMODAT 1 #define HAVE_FCHOWN 1 #define HAVE_FCHOWNAT 1 #define HAVE_FDATASYNC 1 #define HAVE_FDOPENDIR 1 #define HAVE_FLOCK 1 #define HAVE_FORK 1 #define HAVE_FPATHCONF 1 #define HAVE_FTRUNCATE 1 #define HAVE_FUTIMENS 1 #define HAVE_FUTIMES 1 #define HAVE_FUTIMESAT 1 #define HAVE_FSTATAT 1 #define HAVE_FSYNC 1 #define HAVE_GETENTROPY 1 #define HAVE_GETLOADAVG 1 #define HAVE_FSTATVFS 1 /* #undef HAVE_FEXECVE */ /* #undef HAVE_FTIME */ /* #define HAVE_GETGROUPS 1 */ /* #define HAVE_SETGROUPS 1 */ /* #define HAVE_INITGROUPS 1 */ /* #define HAVE_GETGROUPLIST 1 */ #define HAVE_FSEEKO 1 #define HAVE_FTELLO 1 #define HAVE_GETC_UNLOCKED 1 #define HAVE_GETADDRINFO 1 #define HAVE_GAI_STRERROR 1 #define HAVE_GETHOSTBYNAME 1 /* #undef HAVE_GETHOSTBYNAME_R */ /* #undef HAVE_GETHOSTBYNAME_R_3_ARG */ /* #undef HAVE_GETHOSTBYNAME_R_5_ARG */ /* #undef HAVE_GETHOSTBYNAME_R_6_ARG */ #define HAVE_GETRESGID 1 #define HAVE_GETRESUID 1 /* #undef HAVE_GETSPENT */ /* #undef HAVE_GETSPNAM */ /* Define to 1 if you have the `getwd' function. */ /* #undef HAVE_GETWD */ /* Define if you have the 'hstrerror' function. */ /* #undef HAVE_HSTRERROR */ /* Define this if you have le64toh() */ #define HAVE_HTOLE64 1 /* Define to 1 if you have the 'if_nameindex' function. */ /* #undef HAVE_IF_NAMEINDEX */ /* Define if you have the 'inet_aton' function. */ #define HAVE_INET_ATON 1 /* Define if you have the 'inet_pton' function. */ #define HAVE_INET_PTON 1 /* Define if gcc has the ipa-pure-const bug. */ #define HAVE_IPA_PURE_CONST_BUG 1 /* Define to 1 if you have the `kill' function. */ #define HAVE_KILL 1 /* Define to 1 if you have the `killpg' function. */ #define HAVE_KILLPG 1 /* Define if you have the 'kqueue' functions. */ /* #undef HAVE_KQUEUE */ /* Defined to enable large file support when an off_t is bigger than a long and long long is available and at least as big as an off_t. You may need to add some flags for configuration and compilation to enable this mode. (For Solaris and Linux, the necessary defines are already defined.) */ #define HAVE_LARGEFILE_SUPPORT 1 #define HAVE_GETLOGIN 1 #define HAVE_LCHOWN 1 #define HAVE_LCHMOD 1 /* #undef HAVE_LCHFLAGS */ /* Define to 1 if you have the `dl' library (-ldl). */ /* #undef HAVE_LIBDL */ /* Define to 1 if you have the `dld' library (-ldld). */ /* #undef HAVE_LIBDLD */ /* Define to 1 if you have the `ieee' library (-lieee). */ /* #undef HAVE_LIBIEEE */ /* Define to 1 if you have the `resolv' library (-lresolv). */ /* #undef HAVE_LIBRESOLV */ /* Define to 1 if you have the `sendfile' library (-lsendfile). */ /* #undef HAVE_LIBSENDFILE */ /* Define if compiling using Linux 3.6 or later. */ /* #undef HAVE_LINUX_CAN_RAW_FD_FRAMES */ /* Define to 1 if you have the 'lockf' function and the F_LOCK macro. */ #define HAVE_LOCKF 1 /* #define HAVE_DEVICE_MACROS 1 */ #define HAVE_MAKEDEV 1 #define HAVE_MKDIRAT 1 #define HAVE_MBRTOWC 1 #define HAVE_MEMMOVE 1 #define HAVE_MEMRCHR 1 #define HAVE_SEM_GETVALUE 1 #define HAVE_SEM_OPEN 1 #define HAVE_SEM_TIMEDWAIT 1 #define HAVE_SEM_UNLINK 1 /* #define HAVE_MKNOD 1 */ /* #define HAVE_MKNODAT 1 */ /* #define HAVE_MKFIFO 1 */ /* #define HAVE_MKFIFOAT 1 */ /* #define HAVE_SETHOSTNAME 1 */ #define HAVE_DIRENT_H 1 #define HAVE_GETPPID 1 #define HAVE_LINK 1 #define HAVE_LINKAT 1 #define HAVE_LSTAT 1 #define HAVE_LUTIMES 1 #define HAVE_MKTIME 1 #define HAVE_MMAP 1 #define HAVE_NICE 1 #define HAVE_OPENAT 1 #define HAVE_PATHCONF 1 #define HAVE_PAUSE 1 #define HAVE_PIPE 1 #define HAVE_PIPE2 1 #define HAVE_POLL 1 #define HAVE_POSIX_FADVISE 1 #define HAVE_PREAD 1 #define HAVE_PUTENV 1 #define HAVE_PWRITE 1 #define HAVE_READLINK 1 #define HAVE_READLINKAT 1 #define HAVE_READV 1 #define HAVE_REALPATH 1 #define HAVE_RENAMEAT 1 #define HAVE_SELECT 1 #define HAVE_SENDFILE 1 #define HAVE_SETEGID 1 #define HAVE_SETEUID 1 #define HAVE_SETGID 1 #define HAVE_SETITIMER 1 #define HAVE_SETLOCALE 1 #define HAVE_SETPGID 1 #define HAVE_SETPRIORITY 1 #define HAVE_SETREGID 1 #define HAVE_SETRESGID 1 #define HAVE_SETRESUID 1 #define HAVE_SETREUID 1 #define HAVE_SETSID 1 #define HAVE_SETUID 1 #define HAVE_SETVBUF 1 #define HAVE_SIGACTION 1 #define HAVE_SIGALTSTACK 1 #define HAVE_SIGINTERRUPT 1 #define HAVE_SOCKADDR_STORAGE 1 #define HAVE_SYMLINK 1 #define HAVE_SYMLINKAT 1 #define HAVE_SYNC 1 #define HAVE_SYSCONF 1 #define HAVE_TCGETPGRP 1 #define HAVE_TCSETPGRP 1 #define HAVE_TEMPNAM 1 #define HAVE_TIMEGM 1 #define HAVE_TIMES 1 #define HAVE_TMPFILE 1 #define HAVE_TRUNCATE 1 #define HAVE_UNAME 1 #define HAVE_UNLINKAT 1 #define HAVE_UNSETENV 1 #define HAVE_UTIMENSAT 1 #define HAVE_UTIMES 1 #define HAVE_WAIT 1 #define HAVE_WAIT3 1 #define HAVE_WAIT4 1 #define HAVE_WAITPID 1 #define HAVE_STATVFS 1 /* #define HAVE_MREMAP 1 */ /* #undef HAVE_PLOCK */ /* #undef HAVE_POSIX_FALLOCATE */ /* #undef HAVE_PRLIMIT */ /* #undef HAVE_WAITID */ /* #undef HAVE_TMPNAM */ /* #undef HAVE_TMPNAM_R */ /* #undef HAVE_SETPGRP */ /* #undef HAVE_STAT_TV_NSEC2 */ /* #undef HAVE_SIGPENDING */ /* #undef HAVE_SIGRELSE */ /* #undef HAVE_SIGTIMEDWAIT */ /* #undef HAVE_SIGWAIT */ /* #undef HAVE_SIGWAITINFO */ /* #undef HAVE_SOCKADDR_ALG */ /* #undef HAVE_SOCKADDR_SA_LEN */ /* #undef HAVE_STD_ATOMIC */ #define HAVE_SNPRINTF 1 #define HAVE_STRDUP 1 #define HAVE_STRFTIME 1 #define HAVE_STRLCPY 1 #define HAVE_WMEMCMP 1 /* #undef HAVE_WCSCOLL */ /* #undef HAVE_WCSFTIME */ /* #undef HAVE_WCSXFRM */ #define HAVE_USABLE_WCHAR_T 1 #define HAVE_SOCKETPAIR 1 #define HAVE_SSIZE_T 1 #define HAVE_STAT_TV_NSEC 1 #define HAVE_STRUCT_PASSWD_PW_GECOS 1 #define HAVE_STRUCT_PASSWD_PW_PASSWD 1 #define HAVE_STRUCT_STAT_ST_BIRTHTIME 1 #define HAVE_STRUCT_STAT_ST_BLKSIZE 1 #define HAVE_STRUCT_STAT_ST_BLOCKS 1 #define HAVE_STRUCT_STAT_ST_FLAGS 1 #define HAVE_STRUCT_STAT_ST_GEN 1 #define HAVE_STRUCT_STAT_ST_RDEV 1 #define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1 /* #undef HAVE_UCS4_TCL */ /* Define to 1 if you have the `writev' function. */ #define HAVE_WRITEV 1 /* Define if the zlib library has inflateCopy */ #define HAVE_ZLIB_COPY 1 /* Define if log1p(-0.) is 0. rather than -0. */ /* #undef LOG1P_DROPS_ZERO_SIGN */ /* Define to 1 if `major', `minor', and `makedev' are declared in <mkdev.h>. */ /* #undef MAJOR_IN_MKDEV */ /* Define to 1 if `major', `minor', and `makedev' are declared in <sysmacros.h>. */ /* #undef MAJOR_IN_SYSMACROS */ /* Define if mvwdelch in curses.h is an expression. */ #define MVWDELCH_IS_EXPRESSION 1 /* Define to the address where bug reports for this package should be sent. */ /* #undef PACKAGE_BUGREPORT */ /* Define to the full name of this package. */ /* #undef PACKAGE_NAME */ /* Define to the full name and version of this package. */ /* #undef PACKAGE_STRING */ /* Define to the one symbol short name of this package. */ /* #undef PACKAGE_TARNAME */ /* Define to the home page for this package. */ /* #undef PACKAGE_URL */ /* Define to the version of this package. */ /* #undef PACKAGE_VERSION */ /* Define if POSIX semaphores aren't enabled on your system */ /* #define POSIX_SEMAPHORES_NOT_ENABLED 1 */ /* Defined if PTHREAD_SCOPE_SYSTEM supported. */ /* #undef PTHREAD_SYSTEM_SCHED_SUPPORTED */ #define HAVE_PTHREAD_ATFORK 1 #define HAVE_PTHREAD_DESTRUCTOR 1 /* #undef HAVE_PTHREAD_INIT ??? */ #define HAVE_PTHREAD_KILL 1 #define HAVE_PTHREAD_SIGMASK 1 /* Define as the preferred size in bits of long digits */ /* #undef PYLONG_BITS_IN_DIGIT */ /* Define to printf format modifier for Py_ssize_t */ #define PY_FORMAT_SIZE_T "z" /* Defined if Python is built as a shared library. */ /* #undef Py_ENABLE_SHARED */ /* Define hash algorithm for str, bytes and memoryview. SipHash24: 1, FNV: 2, externally defined: 0 */ /* #undef Py_HASH_ALGORITHM */ /* assume C89 semantics that RETSIGTYPE is always void */ #define RETSIGTYPE void /* Define if setpgrp() must be called as setpgrp(0, 0). */ /* #undef SETPGRP_HAVE_ARG */ #define SIZEOF_DOUBLE __SIZEOF_DOUBLE__ #define SIZEOF_FLOAT __SIZEOF_FLOAT__ #define SIZEOF_FPOS_T 8 #define SIZEOF_INT __SIZEOF_INT__ #define SIZEOF_LONG __SIZEOF_LONG__ #define SIZEOF_LONG_DOUBLE __SIZEOF_LONG_DOUBLE__ #define SIZEOF_LONG_LONG __SIZEOF_LONG_LONG__ #define SIZEOF_OFF_T 8 #define SIZEOF_PID_T 4 #define SIZEOF_SHORT __SIZEOF_SHORT__ #define SIZEOF_SIZE_T __SIZEOF_SIZE_T__ #define SIZEOF_TIME_T 8 #define SIZEOF_UINTPTR_T 8 #define SIZEOF_VOID_P 8 #define SIZEOF_WCHAR_T __SIZEOF_WCHAR_T__ #define SIZEOF__BOOL 1 /* #undef SIZEOF_PTHREAD_T */ /* Define if you can safely include both <sys/select.h> and <sys/time.h> (which you can't on SCO ODT 3.0). */ #define SYS_SELECT_WITH_SYS_TIME 1 /* Define if tanh(-0.) is -0., or if platform doesn't have signed zeros */ #define TANH_PRESERVES_ZERO_SIGN 1 /* Library needed by timemodule.c: librt may be needed for clock_gettime() */ /* #undef TIMEMODULE_LIB */ /* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */ #define TIME_WITH_SYS_TIME 1 /* Define to 1 if your <sys/time.h> declares `struct tm'. */ /* #undef TM_IN_SYS_TIME */ /* Define if you want to use computed gotos in ceval.c. */ #define USE_COMPUTED_GOTOS 1 /* Define to use the C99 inline keyword. */ #define USE_INLINE 1 /* Define if you want SIGFPE handled (see Include/pyfpe.h). */ /* #undef WANT_SIGFPE_HANDLER */ /* Define if WINDOW in curses.h offers a field _flags. */ #define WINDOW_HAS_FLAGS 1 /* Define if you want documentation strings in extension modules */ #if !IsTiny() #define WITH_DOC_STRINGS 1 #endif /* Define if you want to compile in DTrace support */ /* #undef WITH_DTRACE */ /* Define if you want to use the new-style (Openstep, Rhapsody, MacOS) dynamic linker (dyld) instead of the old-style (NextStep) dynamic linker (rld). Dyld is necessary to support frameworks. */ /* #undef WITH_DYLD */ /* Define to 1 if libintl is needed for locale functions. */ /* #undef WITH_LIBINTL */ /* Define if you want to compile in Python-specific mallocs */ #ifndef __SANITIZE_ADDRESS__ #define WITH_PYMALLOC 0 #endif /* Define if you want to compile in rudimentary thread support */ #ifndef WITH_THREAD #define WITH_THREAD 1 #endif /* Define if you want pymalloc to be disabled when running under valgrind */ /* #undef WITH_VALGRIND */ /* Define if arithmetic is subject to x87-style double rounding issue */ /* #undef X87_DOUBLE_ROUNDING */ /* Define to 1 if on MINIX. */ /* #undef _MINIX */ /* Define to 2 if the system does not provide POSIX.1 features except with this defined. */ /* #undef _POSIX_1_SOURCE */ /* Define if you have POSIX threads, and your system does not define that. */ #ifndef _POSIX_THREADS #define _POSIX_THREADS #endif /* #define _Py_MEMORY_SANITIZER */ /* #define HAVE_DEV_PTMX 1 */ /* #define HAVE_OPENPTY 1 */ /* #undef HAVE__GETPTY */ /* #undef HAVE_DEV_PTC */ /* #define HAVE_FORKPTY 1 */ /* #define HAVE_SETGROUPS 1 */ /* define to 1 if your sem_getvalue is broken. */ /* #define HAVE_BROKEN_SEM_GETVALUE 1 */ /* Define if --enable-ipv6 is specified */ /* #undef ENABLE_IPV6 */ /* Define if flock needs to be linked with bsd library. */ /* #undef FLOCK_NEEDS_LIBBSD */ /* Define if getpgrp() must be called as getpgrp(0). */ /* #undef GETPGRP_HAVE_ARG */ /* Define to 1 if you have the `bind_textdomain_codeset' function. */ /* #undef HAVE_BIND_TEXTDOMAIN_CODESET */ /* Define if mbstowcs(NULL, "text", 0) does not return the number of wide chars that would be converted. */ /* #undef HAVE_BROKEN_MBSTOWCS */ /* Define if nice() returns success/failure instead of the new priority. */ /* #undef HAVE_BROKEN_NICE */ /* Define if the system reports an invalid PIPE_BUF value. */ /* #undef HAVE_BROKEN_PIPE_BUF */ /* Define if poll() sets errno on invalid file descriptors. */ /* #undef HAVE_BROKEN_POLL */ /* Define if the Posix semaphores do not work on your system */ /* #undef HAVE_BROKEN_POSIX_SEMAPHORES */ /* Define if pthread_sigmask() does not work on your system. */ /* #undef HAVE_BROKEN_PTHREAD_SIGMASK */ /* Define if `unsetenv` does not return an int. */ /* #undef HAVE_BROKEN_UNSETENV */ #define HAVE_SCHED_SETAFFINITY 1 #define HAVE_SCHED_SETPARAM 1 #define HAVE_SCHED_SETSCHEDULER 1 #define HAVE_SCHED_GET_PRIORITY_MAX 1 #define HAVE_SCHED_RR_GET_INTERVAL 1 #define Py_NSIG 32 #define HAVE_SYSTEM 1 #define SELECT_USES_HEAP 1 #define OPENSSL_NO_SCRYPT 1 #define OPENSSL_NO_COMP 1 #define HAVE_LANGINFO_H 1 #if IsModeDbg() #define Py_DEBUG 1 #endif /* #define FAST_LOOPS 1 /\* froot loops *\/ */ #ifdef __SANITIZE_UNDEFINED__ #define HAVE_ALIGNED_REQUIRED 1 #endif #endif /*Py_PYCONFIG_H*/
17,199
582
jart/cosmopolitan
false
cosmopolitan/third_party/python/pythontester.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "third_party/python/Include/yoink.h" #include "third_party/python/runpythonmodule.h" #include "tool/args/args.h" // clang-format off int main(int argc, char **argv) { LoadZipArgs(&argc, &argv); __nosync = 0x5453455454534146; return RunPythonModule(argc, argv); }
1,161
21
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/Python.asdl
-- ASDL's 7 builtin types are: -- identifier, int, string, bytes, object, singleton, constant -- -- singleton: None, True or False -- constant can be None, whereas None means "no value" for object. module Python { mod = Module(stmt* body) | Interactive(stmt* body) | Expression(expr body) -- not really an actual node but useful in Jython's typesystem. | Suite(stmt* body) stmt = FunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns) | AsyncFunctionDef(identifier name, arguments args, stmt* body, expr* decorator_list, expr? returns) | ClassDef(identifier name, expr* bases, keyword* keywords, stmt* body, expr* decorator_list) | Return(expr? value) | Delete(expr* targets) | Assign(expr* targets, expr value) | AugAssign(expr target, operator op, expr value) -- 'simple' indicates that we annotate simple name without parens | AnnAssign(expr target, expr annotation, expr? value, int simple) -- use 'orelse' because else is a keyword in target languages | For(expr target, expr iter, stmt* body, stmt* orelse) | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse) | While(expr test, stmt* body, stmt* orelse) | If(expr test, stmt* body, stmt* orelse) | With(withitem* items, stmt* body) | AsyncWith(withitem* items, stmt* body) | Raise(expr? exc, expr? cause) | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody) | Assert(expr test, expr? msg) | Import(alias* names) | ImportFrom(identifier? module, alias* names, int? level) | Global(identifier* names) | Nonlocal(identifier* names) | Expr(expr value) | Pass | Break | Continue -- XXX Jython will be different -- col_offset is the byte offset in the utf8 string the parser uses attributes (int lineno, int col_offset) -- BoolOp() can use left & right? expr = BoolOp(boolop op, expr* values) | BinOp(expr left, operator op, expr right) | UnaryOp(unaryop op, expr operand) | Lambda(arguments args, expr body) | IfExp(expr test, expr body, expr orelse) | Dict(expr* keys, expr* values) | Set(expr* elts) | ListComp(expr elt, comprehension* generators) | SetComp(expr elt, comprehension* generators) | DictComp(expr key, expr value, comprehension* generators) | GeneratorExp(expr elt, comprehension* generators) -- the grammar constrains where yield expressions can occur | Await(expr value) | Yield(expr? value) | YieldFrom(expr value) -- need sequences for compare to distinguish between -- x < 4 < 3 and (x < 4) < 3 | Compare(expr left, cmpop* ops, expr* comparators) | Call(expr func, expr* args, keyword* keywords) | Num(object n) -- a number as a PyObject. | Str(string s) -- need to specify raw, unicode, etc? | FormattedValue(expr value, int? conversion, expr? format_spec) | JoinedStr(expr* values) | Bytes(bytes s) | NameConstant(singleton value) | Ellipsis | Constant(constant value) -- the following expression can appear in assignment context | Attribute(expr value, identifier attr, expr_context ctx) | Subscript(expr value, slice slice, expr_context ctx) | Starred(expr value, expr_context ctx) | Name(identifier id, expr_context ctx) | List(expr* elts, expr_context ctx) | Tuple(expr* elts, expr_context ctx) -- col_offset is the byte offset in the utf8 string the parser uses attributes (int lineno, int col_offset) expr_context = Load | Store | Del | AugLoad | AugStore | Param slice = Slice(expr? lower, expr? upper, expr? step) | ExtSlice(slice* dims) | Index(expr value) boolop = And | Or operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift | RShift | BitOr | BitXor | BitAnd | FloorDiv unaryop = Invert | Not | UAdd | USub cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn comprehension = (expr target, expr iter, expr* ifs, int is_async) excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body) attributes (int lineno, int col_offset) arguments = (arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults, arg? kwarg, expr* defaults) arg = (identifier arg, expr? annotation) attributes (int lineno, int col_offset) -- keyword arguments supplied to call (NULL identifier for **kwargs) keyword = (identifier? arg, expr value) -- import name with optional 'as' alias. alias = (identifier name, identifier? asname) withitem = (expr context_expr, expr? optional_vars) }
5,169
133
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/metagrammar.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/metagrammar.h" #include "third_party/python/Include/pgen.h" #include "third_party/python/Include/pgenheaders.h" /* clang-format off */ static arc arcs_0_0[3] = { {2, 0}, {3, 0}, {4, 1}, }; static arc arcs_0_1[1] = { {0, 1}, }; static state states_0[2] = { {.s_narcs=3, .s_arc=arcs_0_0}, {.s_narcs=1, .s_arc=arcs_0_1}, }; static arc arcs_1_0[1] = { {5, 1}, }; static arc arcs_1_1[1] = { {6, 2}, }; static arc arcs_1_2[1] = { {7, 3}, }; static arc arcs_1_3[1] = { {3, 4}, }; static arc arcs_1_4[1] = { {0, 4}, }; static state states_1[5] = { {.s_narcs=1, .s_arc=arcs_1_0}, {.s_narcs=1, .s_arc=arcs_1_1}, {.s_narcs=1, .s_arc=arcs_1_2}, {.s_narcs=1, .s_arc=arcs_1_3}, {.s_narcs=1, .s_arc=arcs_1_4}, }; static arc arcs_2_0[1] = { {8, 1}, }; static arc arcs_2_1[2] = { {9, 0}, {0, 1}, }; static state states_2[2] = { {.s_narcs=1, .s_arc=arcs_2_0}, {.s_narcs=2, .s_arc=arcs_2_1}, }; static arc arcs_3_0[1] = { {10, 1}, }; static arc arcs_3_1[2] = { {10, 1}, {0, 1}, }; static state states_3[2] = { {.s_narcs=1, .s_arc=arcs_3_0}, {.s_narcs=2, .s_arc=arcs_3_1}, }; static arc arcs_4_0[2] = { {11, 1}, {13, 2}, }; static arc arcs_4_1[1] = { {7, 3}, }; static arc arcs_4_2[3] = { {14, 4}, {15, 4}, {0, 2}, }; static arc arcs_4_3[1] = { {12, 4}, }; static arc arcs_4_4[1] = { {0, 4}, }; static state states_4[5] = { {.s_narcs=2, .s_arc=arcs_4_0}, {.s_narcs=1, .s_arc=arcs_4_1}, {.s_narcs=3, .s_arc=arcs_4_2}, {.s_narcs=1, .s_arc=arcs_4_3}, {.s_narcs=1, .s_arc=arcs_4_4}, }; static arc arcs_5_0[3] = { {5, 1}, {16, 1}, {17, 2}, }; static arc arcs_5_1[1] = { {0, 1}, }; static arc arcs_5_2[1] = { {7, 3}, }; static arc arcs_5_3[1] = { {18, 1}, }; static state states_5[4] = { {.s_narcs=3, .s_arc=arcs_5_0}, {.s_narcs=1, .s_arc=arcs_5_1}, {.s_narcs=1, .s_arc=arcs_5_2}, {.s_narcs=1, .s_arc=arcs_5_3}, }; static dfa dfas[6] = { {256, "MSTART", 0, 2, states_0, "\070\000\000"}, {257, "RULE", 0, 5, states_1, "\040\000\000"}, {258, "RHS", 0, 2, states_2, "\040\010\003"}, {259, "ALT", 0, 2, states_3, "\040\010\003"}, {260, "ITEM", 0, 5, states_4, "\040\010\003"}, {261, "ATOM", 0, 4, states_5, "\040\000\003"}, }; static label labels[19] = { {0, "EMPTY"}, {256, 0}, {257, 0}, {4, 0}, {0, 0}, {1, 0}, {11, 0}, {258, 0}, {259, 0}, {18, 0}, {260, 0}, {9, 0}, {10, 0}, {261, 0}, {16, 0}, {14, 0}, {3, 0}, {7, 0}, {8, 0}, }; static grammar _PyParser_Grammarz = { 6, dfas, {19, labels}, 256 }; grammar * meta_grammar(void) { return &_PyParser_Grammarz; } grammar * Py_meta_grammar(void) { return meta_grammar(); }
3,743
167
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/myreadline.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/errno.h" #include "libc/limits.h" #include "libc/log/log.h" #include "libc/stdio/stdio.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/intrcheck.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" /* clang-format off */ /* Readline interface for tokenizer.c and [raw_]input() in bltinmodule.c. By default, or when stdin is not a tty device, we have a super simple my_readline function using fgets. Optionally, we can use the GNU readline library. my_readline() has a different return value from GNU readline(): - NULL if an interrupt occurred or if an error occurred - a malloc'ed empty string if EOF was read - a malloc'ed string ending in \n normally */ PyThreadState* _PyOS_ReadlineTState; #ifdef WITH_THREAD #include "third_party/python/Include/pythread.h" static PyThread_type_lock _PyOS_ReadlineLock = NULL; #endif int (*PyOS_InputHook)(void) = NULL; /* This function restarts a fgets() after an EINTR error occurred except if PyOS_InterruptOccurred() returns true. */ static int my_fgets(char *buf, int len, FILE *fp) { char *p; int err; while (1) { if (PyOS_InputHook != NULL) (void)(PyOS_InputHook)(); errno = 0; clearerr(fp); p = fgets(buf, len, fp); if (p != NULL) return 0; /* No error */ err = errno; if (feof(fp)) { clearerr(fp); return -1; /* EOF */ } #ifdef EINTR if (err == EINTR) { int s; #ifdef WITH_THREAD PyEval_RestoreThread(_PyOS_ReadlineTState); #endif s = PyErr_CheckSignals(); #ifdef WITH_THREAD PyEval_SaveThread(); #endif if (s < 0) return 1; /* try again */ continue; } #endif if (PyOS_InterruptOccurred()) { return 1; /* Interrupt */ } return -2; /* Error */ } /* NOTREACHED */ } #ifdef MS_WINDOWS /* Readline implementation using ReadConsoleW */ extern char _get_console_type(HANDLE handle); char * _PyOS_WindowsConsoleReadline(HANDLE hStdIn) { static wchar_t wbuf_local[1024 * 16]; const DWORD chunk_size = 1024; DWORD n_read, total_read, wbuflen, u8len; wchar_t *wbuf; char *buf = NULL; int err = 0; n_read = (DWORD)-1; total_read = 0; wbuf = wbuf_local; wbuflen = sizeof(wbuf_local) / sizeof(wbuf_local[0]) - 1; while (1) { if (PyOS_InputHook != NULL) { (void)(PyOS_InputHook)(); } if (!ReadConsoleW(hStdIn, &wbuf[total_read], wbuflen - total_read, &n_read, NULL)) { err = GetLastError(); goto exit; } if (n_read == (DWORD)-1 && (err = GetLastError()) == ERROR_OPERATION_ABORTED) { break; } if (n_read == 0) { int s; err = GetLastError(); if (err != ERROR_OPERATION_ABORTED) goto exit; err = 0; HANDLE hInterruptEvent = _PyOS_SigintEvent(); if (WaitForSingleObjectEx(hInterruptEvent, 100, FALSE) == WAIT_OBJECT_0) { ResetEvent(hInterruptEvent); #ifdef WITH_THREAD PyEval_RestoreThread(_PyOS_ReadlineTState); #endif s = PyErr_CheckSignals(); #ifdef WITH_THREAD PyEval_SaveThread(); #endif if (s < 0) goto exit; } break; } total_read += n_read; if (total_read == 0 || wbuf[total_read - 1] == L'\n') { break; } wbuflen += chunk_size; if (wbuf == wbuf_local) { wbuf[total_read] = '\0'; wbuf = (wchar_t*)PyMem_RawMalloc(wbuflen * sizeof(wchar_t)); if (wbuf) wcscpy_s(wbuf, wbuflen, wbuf_local); else { PyErr_NoMemory(); goto exit; } } else { wchar_t *tmp = PyMem_RawRealloc(wbuf, wbuflen * sizeof(wchar_t)); if (tmp == NULL) { PyErr_NoMemory(); goto exit; } wbuf = tmp; } } if (wbuf[0] == '\x1a') { buf = PyMem_RawMalloc(1); if (buf) buf[0] = '\0'; else { PyErr_NoMemory(); } goto exit; } u8len = WideCharToMultiByte(CP_UTF8, 0, wbuf, total_read, NULL, 0, NULL, NULL); buf = PyMem_RawMalloc(u8len + 1); if (buf == NULL) { PyErr_NoMemory(); goto exit; } u8len = WideCharToMultiByte(CP_UTF8, 0, wbuf, total_read, buf, u8len, NULL, NULL); buf[u8len] = '\0'; exit: if (wbuf != wbuf_local) PyMem_RawFree(wbuf); if (err) { #ifdef WITH_THREAD PyEval_RestoreThread(_PyOS_ReadlineTState); #endif PyErr_SetFromWindowsErr(err); #ifdef WITH_THREAD PyEval_SaveThread(); #endif } return buf; } #endif /* Readline implementation using fgets() */ char * PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt) { size_t n; char *p, *pr; #ifdef MS_WINDOWS if (!Py_LegacyWindowsStdioFlag && sys_stdin == stdin) { HANDLE hStdIn, hStdErr; _Py_BEGIN_SUPPRESS_IPH hStdIn = (HANDLE)_get_osfhandle(fileno(sys_stdin)); hStdErr = (HANDLE)_get_osfhandle(fileno(stderr)); _Py_END_SUPPRESS_IPH if (_get_console_type(hStdIn) == 'r') { fflush(sys_stdout); if (prompt) { if (_get_console_type(hStdErr) == 'w') { wchar_t *wbuf; int wlen; wlen = MultiByteToWideChar(CP_UTF8, 0, prompt, -1, NULL, 0); if (wlen) { wbuf = PyMem_RawMalloc(wlen * sizeof(wchar_t)); if (wbuf == NULL) { PyErr_NoMemory(); return NULL; } wlen = MultiByteToWideChar(CP_UTF8, 0, prompt, -1, wbuf, wlen); if (wlen) { DWORD n; fflush(stderr); /* wlen includes null terminator, so subtract 1 */ WriteConsoleW(hStdErr, wbuf, wlen - 1, &n, NULL); } PyMem_RawFree(wbuf); } } else { fprintf(stderr, "%s", prompt); fflush(stderr); } } clearerr(sys_stdin); return _PyOS_WindowsConsoleReadline(hStdIn); } } #endif n = 100; p = (char *)PyMem_RawMalloc(n); if (p == NULL) { PyErr_NoMemory(); return NULL; } fflush(sys_stdout); if (prompt) fprintf(stderr, "%s", prompt); fflush(stderr); switch (my_fgets(p, (int)n, sys_stdin)) { case 0: /* Normal case */ break; case 1: /* Interrupt */ PyMem_RawFree(p); return NULL; case -1: /* EOF */ case -2: /* Error */ default: /* Shouldn't happen */ *p = '\0'; break; } n = strlen(p); while (n > 0 && p[n-1] != '\n') { size_t incr = n+2; if (incr > INT_MAX) { PyMem_RawFree(p); PyErr_SetString(PyExc_OverflowError, "input line too long"); return NULL; } pr = (char *)PyMem_RawRealloc(p, n + incr); if (pr == NULL) { PyMem_RawFree(p); PyErr_NoMemory(); return NULL; } p = pr; if (my_fgets(p+n, (int)incr, sys_stdin) != 0) break; n += strlen(p+n); } pr = (char *)PyMem_RawRealloc(p, n+1); if (pr == NULL) { PyMem_RawFree(p); PyErr_NoMemory(); return NULL; } return pr; } /* By initializing this function pointer, systems embedding Python can override the readline function. Note: Python expects in return a buffer allocated with PyMem_Malloc. */ char *(*PyOS_ReadlineFunctionPointer)(FILE *, FILE *, const char *); /* Interface used by tokenizer.c and bltinmodule.c */ char * PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt) { char *rv, *res; size_t len; if (_PyOS_ReadlineTState == PyThreadState_GET()) { PyErr_SetString(PyExc_RuntimeError, "can't re-enter readline"); return NULL; } if (PyOS_ReadlineFunctionPointer == NULL) { PyOS_ReadlineFunctionPointer = PyOS_StdioReadline; } #ifdef WITH_THREAD if (_PyOS_ReadlineLock == NULL) { _PyOS_ReadlineLock = PyThread_allocate_lock(); if (_PyOS_ReadlineLock == NULL) { PyErr_SetString(PyExc_MemoryError, "can't allocate lock"); return NULL; } } #endif _PyOS_ReadlineTState = PyThreadState_GET(); Py_BEGIN_ALLOW_THREADS #ifdef WITH_THREAD PyThread_acquire_lock(_PyOS_ReadlineLock, 1); #endif /* This is needed to handle the unlikely case that the * interpreter is in interactive mode *and* stdin/out are not * a tty. This can happen, for example if python is run like * this: python -i < test1.py */ if (!isatty (fileno (sys_stdin)) || !isatty (fileno (sys_stdout))) rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt); else rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout, prompt); Py_END_ALLOW_THREADS #ifdef WITH_THREAD PyThread_release_lock(_PyOS_ReadlineLock); #endif _PyOS_ReadlineTState = NULL; if (rv == NULL) return NULL; len = strlen(rv) + 1; res = PyMem_Malloc(len); if (res != NULL) { memcpy(res, rv, len); } else { PyErr_NoMemory(); } PyMem_RawFree(rv); return res; }
10,989
382
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/pgenmain.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PGEN #include "libc/log/log.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/parsetok.h" #include "third_party/python/Include/pgen.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" /* clang-format off */ /* This expects a filename containing the grammar as argv[1] (UNIX) or asks the console for such a file name (THINK C). It writes its output on two files in the current directory: - "graminit.c" gets the grammar as a bunch of initialized data - "graminit.h" gets the grammar's non-terminals as #defines. Error messages and status info during the generation process are written to stdout, or sometimes to stderr. */ /* XXX TO DO: - check for duplicate definitions of names (instead of fatal err) */ int Py_DebugFlag; int Py_VerboseFlag; int Py_IgnoreEnvironmentFlag; /* Forward */ grammar *getgrammar(const char *filename); void Py_Exit(int) _Py_NO_RETURN; void Py_Exit(int sts) { exit(sts); } #ifdef WITH_THREAD /* Needed by obmalloc.c */ int PyGILState_Check(void) { return 1; } #endif void _PyMem_DumpTraceback(int fd, const void *ptr) {} int main(int argc, char **argv) { grammar *g; FILE *fp; char *filename, *graminit_h, *graminit_c; if (argc != 4) { fprintf(stderr, "usage: %s grammar graminit.h graminit.c\n", argv[0]); Py_Exit(2); } filename = argv[1]; graminit_h = argv[2]; graminit_c = argv[3]; g = getgrammar(filename); fp = fopen(graminit_c, "w"); if (fp == NULL) { perror(graminit_c); Py_Exit(1); } if (Py_DebugFlag) printf("Writing %s ...\n", graminit_c); printgrammar(g, fp); fclose(fp); fp = fopen(graminit_h, "w"); if (fp == NULL) { perror(graminit_h); Py_Exit(1); } if (Py_DebugFlag) printf("Writing %s ...\n", graminit_h); printnonterminals(g, fp); fclose(fp); freegrammar(g); Py_Exit(0); return 0; /* Make gcc -Wall happy */ } grammar * getgrammar(const char *filename) { FILE *fp; node *n; grammar *g0, *g; perrdetail err; fp = fopen(filename, "r"); if (fp == NULL) { perror(filename); Py_Exit(1); } g0 = meta_grammar(); n = PyParser_ParseFile(fp, filename, g0, g0->g_start, (char *)NULL, (char *)NULL, &err); fclose(fp); if (n == NULL) { fprintf(stderr, "Parsing error %d, line %d.\n", err.error, err.lineno); if (err.text != NULL) { size_t len; int i; fprintf(stderr, "%s", err.text); len = strlen(err.text); if (len == 0 || err.text[len-1] != '\n') fprintf(stderr, "\n"); for (i = 0; i < err.offset; i++) { if (err.text[i] == '\t') putc('\t', stderr); else putc(' ', stderr); } fprintf(stderr, "^\n"); PyObject_FREE(err.text); } Py_Exit(1); } g = pgen(n); PyNode_Free(n); if (g == NULL) { printf("Bad grammar.\n"); Py_Exit(1); } return g; } /* Can't happen in pgen */ PyObject* PyErr_Occurred() { return 0; } void Py_FatalError(const char *msg) { fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg); Py_Exit(1); } /* No-nonsense my_readline() for tokenizer.c */ char * PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, const char *prompt) { size_t n = 1000; char *p = (char *)PyMem_MALLOC(n); char *q; if (p == NULL) return NULL; fprintf(stderr, "%s", prompt); q = fgets(p, n, sys_stdin); if (q == NULL) { *p = '\0'; return p; } n = strlen(p); if (n > 0 && p[n-1] != '\n') p[n-1] = '\n'; return (char *)PyMem_REALLOC(p, n+1); } /* No-nonsense fgets */ char * Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj) { return fgets(buf, n, stream); } void PySys_WriteStderr(const char *format, ...) { va_list va; va_start(va, format); vfprintf(stderr, format, va); va_end(va); }
5,155
193
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/listnode.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/stdio/stdio.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Include/token.h" /* clang-format off */ static void list1node(FILE *, node *); static void listnode(FILE *, node *); void PyNode_ListTree(node *n) { listnode(stdout, n); } static int level, atbol; static void listnode(FILE *fp, node *n) { level = 0; atbol = 1; list1node(fp, n); } static void list1node(FILE *fp, node *n) { if (n == 0) return; if (ISNONTERMINAL(TYPE(n))) { int i; for (i = 0; i < NCH(n); i++) list1node(fp, CHILD(n, i)); } else if (ISTERMINAL(TYPE(n))) { switch (TYPE(n)) { case INDENT: ++level; break; case DEDENT: --level; break; default: if (atbol) { int i; for (i = 0; i < level; ++i) fprintf(fp, "\t"); atbol = 0; } if (TYPE(n) == NEWLINE) { if (STR(n) != NULL) fprintf(fp, "%s", STR(n)); fprintf(fp, "\n"); atbol = 1; } else fprintf(fp, "%s ", STR(n)); break; } } else fprintf(fp, "? "); }
2,186
71
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/grammar.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/mem/mem.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/token.h" /* clang-format off */ extern int Py_DebugFlag; grammar * newgrammar(int start) { grammar *g; g = (grammar *)PyObject_MALLOC(sizeof(grammar)); if (g == NULL) Py_FatalError("no mem for new grammar"); g->g_ndfas = 0; g->g_dfa = NULL; g->g_start = start; g->g_ll.ll_nlabels = 0; g->g_ll.ll_label = NULL; g->g_accel = 0; return g; } void freegrammar(grammar *g) { int i; for (i = 0; i < g->g_ndfas; i++) { free(g->g_dfa[i].d_name); for (int j = 0; j < g->g_dfa[i].d_nstates; j++) PyObject_FREE(g->g_dfa[i].d_state[j].s_arc); PyObject_FREE(g->g_dfa[i].d_state); } PyObject_FREE(g->g_dfa); for (i = 0; i < g->g_ll.ll_nlabels; i++) free(g->g_ll.ll_label[i].lb_str); PyObject_FREE(g->g_ll.ll_label); PyObject_FREE(g); } dfa * adddfa(grammar *g, int type, const char *name) { dfa *d; g->g_dfa = (dfa *)PyObject_REALLOC(g->g_dfa, sizeof(dfa) * (g->g_ndfas + 1)); if (g->g_dfa == NULL) Py_FatalError("no mem to resize dfa in adddfa"); d = &g->g_dfa[g->g_ndfas++]; d->d_type = type; d->d_name = strdup(name); d->d_nstates = 0; d->d_state = NULL; d->d_initial = -1; d->d_first = NULL; return d; /* Only use while fresh! */ } int addstate(dfa *d) { state *s; d->d_state = (state *)PyObject_REALLOC(d->d_state, sizeof(state) * (d->d_nstates + 1)); if (d->d_state == NULL) Py_FatalError("no mem to resize state in addstate"); s = &d->d_state[d->d_nstates++]; s->s_narcs = 0; s->s_arc = NULL; s->s_lower = 0; s->s_upper = 0; s->s_accel = NULL; s->s_accept = 0; return Py_SAFE_DOWNCAST(s - d->d_state, intptr_t, int); } void addarc(dfa *d, int from, int to, int lbl) { state *s; arc *a; assert(0 <= from && from < d->d_nstates); assert(0 <= to && to < d->d_nstates); s = &d->d_state[from]; s->s_arc = (arc *)PyObject_REALLOC(s->s_arc, sizeof(arc) * (s->s_narcs + 1)); if (s->s_arc == NULL) Py_FatalError("no mem to resize arc list in addarc"); a = &s->s_arc[s->s_narcs++]; a->a_lbl = lbl; a->a_arrow = to; } int addlabel(labellist *ll, int type, const char *str) { int i; label *lb; for (i = 0; i < ll->ll_nlabels; i++) { if (ll->ll_label[i].lb_type == type && strcmp(ll->ll_label[i].lb_str, str) == 0) return i; } ll->ll_label = (label *)PyObject_REALLOC(ll->ll_label, sizeof(label) * (ll->ll_nlabels + 1)); if (ll->ll_label == NULL) Py_FatalError("no mem to resize labellist in addlabel"); lb = &ll->ll_label[ll->ll_nlabels++]; lb->lb_type = type; lb->lb_str = strdup(str); if (Py_DebugFlag) printf("Label @ %8p, %d: %s\n", ll, ll->ll_nlabels, PyGrammar_LabelRepr(lb)); return Py_SAFE_DOWNCAST(lb - ll->ll_label, intptr_t, int); } /* Same, but rather dies than adds */ int findlabel(labellist *ll, int type, const char *str) { int i; for (i = 0; i < ll->ll_nlabels; i++) { if (ll->ll_label[i].lb_type == type /*&& strcmp(ll->ll_label[i].lb_str, str) == 0*/) return i; } fprintf(stderr, "Label %d/'%s' not found\n", type, str); Py_FatalError("grammar.c:findlabel()"); /* Py_FatalError() is declared with __attribute__((__noreturn__)). GCC emits a warning without "return 0;" (compiler bug!), but Clang is smarter and emits a warning on the return... */ #ifndef __clang__ return 0; /* Make gcc -Wall happy */ #endif } /* Forward */ static void translabel(grammar *, label *); void translatelabels(grammar *g) { int i; #ifdef Py_DEBUG printf("Translating labels ...\n"); #endif /* Don't translate EMPTY */ for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++) translabel(g, &g->g_ll.ll_label[i]); } static void translabel(grammar *g, label *lb) { int i; if (Py_DebugFlag) printf("Translating label %s ...\n", PyGrammar_LabelRepr(lb)); if (lb->lb_type == NAME) { for (i = 0; i < g->g_ndfas; i++) { if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) { if (Py_DebugFlag) printf( "Label %s is non-terminal %d.\n", lb->lb_str, g->g_dfa[i].d_type); lb->lb_type = g->g_dfa[i].d_type; free(lb->lb_str); lb->lb_str = NULL; return; } } for (i = 0; i < (int)N_TOKENS; i++) { if (strcmp(lb->lb_str, _PyParser_TokenNames[i]) == 0) { if (Py_DebugFlag) printf("Label %s is terminal %d.\n", lb->lb_str, i); lb->lb_type = i; free(lb->lb_str); lb->lb_str = NULL; return; } } printf("Can't translate NAME label '%s'\n", lb->lb_str); return; } if (lb->lb_type == STRING) { if (isalpha(Py_CHARMASK(lb->lb_str[1])) || lb->lb_str[1] == '_') { char *p; char *src; char *dest; size_t name_len; if (Py_DebugFlag) printf("Label %s is a keyword\n", lb->lb_str); lb->lb_type = NAME; src = lb->lb_str + 1; p = strchr(src, '\''); if (p) name_len = p - src; else name_len = strlen(src); dest = (char *)malloc(name_len + 1); if (!dest) { printf("Can't alloc dest '%s'\n", src); return; } strncpy(dest, src, name_len); dest[name_len] = '\0'; free(lb->lb_str); lb->lb_str = dest; } else if (lb->lb_str[2] == lb->lb_str[0]) { int type = (int) PyToken_OneChar(lb->lb_str[1]); if (type != OP) { lb->lb_type = type; free(lb->lb_str); lb->lb_str = NULL; } else printf("Unknown OP label %s\n", lb->lb_str); } else if (lb->lb_str[2] && lb->lb_str[3] == lb->lb_str[0]) { int type = (int) PyToken_TwoChars(lb->lb_str[1], lb->lb_str[2]); if (type != OP) { lb->lb_type = type; free(lb->lb_str); lb->lb_str = NULL; } else printf("Unknown OP label %s\n", lb->lb_str); } else if (lb->lb_str[2] && lb->lb_str[3] && lb->lb_str[4] == lb->lb_str[0]) { int type = (int) PyToken_ThreeChars(lb->lb_str[1], lb->lb_str[2], lb->lb_str[3]); if (type != OP) { lb->lb_type = type; free(lb->lb_str); lb->lb_str = NULL; } else printf("Unknown OP label %s\n", lb->lb_str); } else printf("Can't translate STRING label %s\n", lb->lb_str); } else printf("Can't translate label '%s'\n", PyGrammar_LabelRepr(lb)); }
8,592
277
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/acceler.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/runtime/runtime.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Include/token.h" #include "third_party/python/Parser/parser.h" /* clang-format off */ /* The parser as originally conceived had disappointing performance. This module does some precomputation that speeds up the selection of a DFA based upon a token, turning a search through an array into a simple indexing operation. The parser now cannot work without the accelerators installed. Note that the accelerators are installed dynamically when the parser is initialized, they are not part of the static data structure written on graminit.[ch] by the parser generator. */ /* Forward references */ static void fixdfa(grammar *, dfa *); static void fixstate(grammar *, state *); void PyGrammar_AddAccelerators(grammar *g) { dfa *d; int i; d = g->g_dfa; for (i = g->g_ndfas; --i >= 0; d++) fixdfa(g, d); g->g_accel = 1; } void PyGrammar_RemoveAccelerators(grammar *g) { dfa *d; int i; g->g_accel = 0; d = g->g_dfa; for (i = g->g_ndfas; --i >= 0; d++) { state *s; int j; s = d->d_state; for (j = 0; j < d->d_nstates; j++, s++) { if (s->s_accel) PyObject_FREE(s->s_accel); s->s_accel = NULL; } } } static void fixdfa(grammar *g, dfa *d) { state *s; int j; s = d->d_state; for (j = 0; j < d->d_nstates; j++, s++) fixstate(g, s); } static optimizespeed void fixstate(grammar *g, state *s) { arc *a; int k; int *accel; int nl = g->g_ll.ll_nlabels; s->s_accept = 0; accel = (int *) PyObject_MALLOC(nl * sizeof(int)); if (accel == NULL) { fprintf(stderr, "no mem to build parser accelerators\n"); exit(1); } for (k = 0; k < nl; k++) accel[k] = -1; a = s->s_arc; for (k = s->s_narcs; --k >= 0; a++) { int lbl = a->a_lbl; label *l = &g->g_ll.ll_label[lbl]; int type = l->lb_type; if (a->a_arrow >= (1 << 7)) { printf("XXX too many states!\n"); continue; } if (ISNONTERMINAL(type)) { dfa *d1 = PyGrammar_FindDFA(g, type); int ibit; if (type - NT_OFFSET >= (1 << 7)) { printf("XXX too high nonterminal number!\n"); continue; } for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) { if (testbit(d1->d_first, ibit)) { if (accel[ibit] != -1) printf("XXX ambiguity!\n"); accel[ibit] = a->a_arrow | (1 << 7) | ((type - NT_OFFSET) << 8); } } } else if (lbl == EMPTY) s->s_accept = 1; else if (lbl >= 0 && lbl < nl) accel[lbl] = a->a_arrow; } while (nl > 0 && accel[nl-1] == -1) nl--; for (k = 0; k < nl && accel[k] == -1;) k++; if (k < nl) { int i; s->s_accel = (int *) PyObject_MALLOC((nl-k) * sizeof(int)); if (s->s_accel == NULL) { fprintf(stderr, "no mem to add parser accelerators\n"); exit(1); } s->s_lower = k; s->s_upper = nl; for (i = 0; k < nl; i++, k++) s->s_accel[i] = accel[k]; } PyObject_FREE(accel); }
4,389
132
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/printgrammar.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PGEN #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/pgenheaders.h" /* clang-format off */ /* Print a bunch of C initializers that represent a grammar */ /* Forward */ static void printarcs(int, dfa *, FILE *); static void printstates(grammar *, FILE *); static void printdfas(grammar *, FILE *); static void printlabels(grammar *, FILE *); void printgrammar(grammar *g, FILE *fp) { fprintf(fp, "/* Generated by Parser/pgen */\n\n"); fprintf(fp, "#include \"pgenheaders.h\"\n"); fprintf(fp, "#include \"grammar.h\"\n"); fprintf(fp, "PyAPI_DATA(grammar) _PyParser_Grammar;\n"); printdfas(g, fp); printlabels(g, fp); fprintf(fp, "grammar _PyParser_Grammar = {\n"); fprintf(fp, " %d,\n", g->g_ndfas); fprintf(fp, " dfas,\n"); fprintf(fp, " {%d, labels},\n", g->g_ll.ll_nlabels); fprintf(fp, " %d\n", g->g_start); fprintf(fp, "};\n"); } void printnonterminals(grammar *g, FILE *fp) { dfa *d; int i; fprintf(fp, "/* Generated by Parser/pgen */\n\n"); d = g->g_dfa; for (i = g->g_ndfas; --i >= 0; d++) fprintf(fp, "#define %s %d\n", d->d_name, d->d_type); } static void printarcs(int i, dfa *d, FILE *fp) { arc *a; state *s; int j, k; s = d->d_state; for (j = 0; j < d->d_nstates; j++, s++) { fprintf(fp, "static arc arcs_%d_%d[%d] = {\n", i, j, s->s_narcs); a = s->s_arc; for (k = 0; k < s->s_narcs; k++, a++) fprintf(fp, " {%d, %d},\n", a->a_lbl, a->a_arrow); fprintf(fp, "};\n"); } } static void printstates(grammar *g, FILE *fp) { state *s; dfa *d; int i, j; d = g->g_dfa; for (i = 0; i < g->g_ndfas; i++, d++) { printarcs(i, d, fp); fprintf(fp, "static state states_%d[%d] = {\n", i, d->d_nstates); s = d->d_state; for (j = 0; j < d->d_nstates; j++, s++) fprintf(fp, " {%d, arcs_%d_%d},\n", s->s_narcs, i, j); fprintf(fp, "};\n"); } } static void printdfas(grammar *g, FILE *fp) { dfa *d; int i, j, n; printstates(g, fp); fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas); d = g->g_dfa; for (i = 0; i < g->g_ndfas; i++, d++) { fprintf(fp, " {%d, \"%s\", %d, %d, states_%d,\n", d->d_type, d->d_name, d->d_initial, d->d_nstates, i); fprintf(fp, " \""); n = NBYTES(g->g_ll.ll_nlabels); for (j = 0; j < n; j++) fprintf(fp, "\\%03o", d->d_first[j] & 0xff); fprintf(fp, "\"},\n"); } fprintf(fp, "};\n"); } static void printlabels(grammar *g, FILE *fp) { label *l; int i; fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels); l = g->g_ll.ll_label; for (i = g->g_ll.ll_nlabels; --i >= 0; l++) { if (l->lb_str == NULL) fprintf(fp, " {%d, 0},\n", l->lb_type); else fprintf(fp, " {%d, \"%s\"},\n", l->lb_type, l->lb_str); } fprintf(fp, "};\n"); }
3,896
126
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/grammar1.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/token.h" /* clang-format off */ /* Return the DFA for the given type */ dfa * PyGrammar_FindDFA(grammar *g, int type) { dfa *d; #if 1 /* Massive speed-up */ d = &g->g_dfa[type - NT_OFFSET]; assert(d->d_type == type); return d; #else /* Old, slow version */ int i; for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) { if (d->d_type == type) return d; } assert(0); /* NOTREACHED */ #endif } const char * PyGrammar_LabelRepr(label *lb) { static char buf[100]; if (lb->lb_type == ENDMARKER) return "EMPTY"; else if (ISNONTERMINAL(lb->lb_type)) { if (lb->lb_str == NULL) { PyOS_snprintf(buf, sizeof(buf), "NT%d", lb->lb_type); return buf; } else return lb->lb_str; } else if (lb->lb_type < N_TOKENS) { if (lb->lb_str == NULL) return _PyParser_TokenNames[lb->lb_type]; else { PyOS_snprintf(buf, sizeof(buf), "%.32s(%.32s)", _PyParser_TokenNames[lb->lb_type], lb->lb_str); return buf; } } else { Py_FatalError("invalid label"); return NULL; } }
2,172
65
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/parsetok.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/errcode.h" #include "third_party/python/Include/graminit.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/parsetok.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Parser/parser.h" #include "third_party/python/Parser/tokenizer.h" /* clang-format off */ static node *parsetok(struct tok_state *, grammar *, int, perrdetail *, int *); static int initerr(perrdetail *err_ret, PyObject * filename); /* Parse input coming from a string. Return error code, print some errors. */ node * PyParser_ParseString(const char *s, grammar *g, int start, perrdetail *err_ret) { return PyParser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, 0); } node * PyParser_ParseStringFlags(const char *s, grammar *g, int start, perrdetail *err_ret, int flags) { return PyParser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, flags); } node * PyParser_ParseStringFlagsFilename(const char *s, const char *filename, grammar *g, int start, perrdetail *err_ret, int flags) { int iflags = flags; return PyParser_ParseStringFlagsFilenameEx(s, filename, g, start, err_ret, &iflags); } node * PyParser_ParseStringObject(const char *s, PyObject *filename, grammar *g, int start, perrdetail *err_ret, int *flags) { struct tok_state *tok; int exec_input = start == file_input; if (initerr(err_ret, filename) < 0) return NULL; if (*flags & PyPARSE_IGNORE_COOKIE) tok = PyTokenizer_FromUTF8(s, exec_input); else tok = PyTokenizer_FromString(s, exec_input); if (tok == NULL) { err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM; return NULL; } #ifndef PGEN Py_INCREF(err_ret->filename); tok->filename = err_ret->filename; #endif return parsetok(tok, g, start, err_ret, flags); } node * PyParser_ParseStringFlagsFilenameEx(const char *s, const char *filename_str, grammar *g, int start, perrdetail *err_ret, int *flags) { node *n; PyObject *filename = NULL; #ifndef PGEN if (filename_str != NULL) { filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) { err_ret->error = E_ERROR; return NULL; } } #endif n = PyParser_ParseStringObject(s, filename, g, start, err_ret, flags); #ifndef PGEN Py_XDECREF(filename); #endif return n; } /* Parse input coming from a file. Return error code, print some errors. */ node * PyParser_ParseFile(FILE *fp, const char *filename, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret) { return PyParser_ParseFileFlags(fp, filename, NULL, g, start, ps1, ps2, err_ret, 0); } node * PyParser_ParseFileFlags(FILE *fp, const char *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int flags) { int iflags = flags; return PyParser_ParseFileFlagsEx(fp, filename, enc, g, start, ps1, ps2, err_ret, &iflags); } 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) { struct tok_state *tok; if (initerr(err_ret, filename) < 0) return NULL; if ((tok = PyTokenizer_FromFile(fp, enc, ps1, ps2)) == NULL) { err_ret->error = E_NOMEM; return NULL; } #ifndef PGEN Py_INCREF(err_ret->filename); tok->filename = err_ret->filename; #endif return parsetok(tok, g, start, err_ret, flags); } node * PyParser_ParseFileFlagsEx(FILE *fp, const char *filename, const char *enc, grammar *g, int start, const char *ps1, const char *ps2, perrdetail *err_ret, int *flags) { node *n; PyObject *fileobj = NULL; #ifndef PGEN if (filename != NULL) { fileobj = PyUnicode_DecodeFSDefault(filename); if (fileobj == NULL) { err_ret->error = E_ERROR; return NULL; } } #endif n = PyParser_ParseFileObject(fp, fileobj, enc, g, start, ps1, ps2, err_ret, flags); #ifndef PGEN Py_XDECREF(fileobj); #endif return n; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 static const char with_msg[] = "%s:%d: Warning: 'with' will become a reserved keyword in Python 2.6\n"; static const char as_msg[] = "%s:%d: Warning: 'as' will become a reserved keyword in Python 2.6\n"; static void warn(const char *msg, const char *filename, int lineno) { if (filename == NULL) filename = "<string>"; PySys_WriteStderr(msg, filename, lineno); } #endif #endif /* Parse input coming from the given tokenizer structure. Return error code. */ static optimizespeed node * parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret, int *flags) { parser_state *ps; node *n; int started = 0; if ((ps = PyParser_New(g, start)) == NULL) { err_ret->error = E_NOMEM; PyTokenizer_Free(tok); return NULL; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (*flags & PyPARSE_BARRY_AS_BDFL) ps->p_flags |= CO_FUTURE_BARRY_AS_BDFL; #endif for (;;) { char *a, *b; int type; size_t len; char *str; int col_offset; type = PyTokenizer_Get(tok, &a, &b); if (type == ERRORTOKEN) { err_ret->error = tok->done; break; } if (type == ENDMARKER && started) { type = NEWLINE; /* Add an extra newline */ started = 0; /* Add the right number of dedent tokens, except if a certain flag is given -- codeop.py uses this. */ if (tok->indent && !(*flags & PyPARSE_DONT_IMPLY_DEDENT)) { tok->pendin = -tok->indent; tok->indent = 0; } } else started = 1; len = (a != NULL && b != NULL) ? b - a : 0; str = (char *) PyObject_MALLOC(len + 1); if (str == NULL) { err_ret->error = E_NOMEM; break; } if (len > 0) strncpy(str, a, len); str[len] = '\0'; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD if (type == NOTEQUAL) { if (!(ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "!=")) { PyObject_FREE(str); err_ret->error = E_SYNTAX; break; } else if ((ps->p_flags & CO_FUTURE_BARRY_AS_BDFL) && strcmp(str, "<>")) { PyObject_FREE(str); err_ret->expected = NOTEQUAL; err_ret->error = E_SYNTAX; break; } } #endif if (a != NULL && a >= tok->line_start) { col_offset = Py_SAFE_DOWNCAST(a - tok->line_start, intptr_t, int); } else { col_offset = -1; } if ((err_ret->error = PyParser_AddToken(ps, (int)type, str, tok->lineno, col_offset, &(err_ret->expected))) != E_OK) { if (err_ret->error != E_DONE) { PyObject_FREE(str); err_ret->token = type; } break; } } if (err_ret->error == E_DONE) { n = ps->p_tree; ps->p_tree = NULL; #ifndef PGEN /* Check that the source for a single input statement really is a single statement by looking at what is left in the buffer after parsing. Trailing whitespace and comments are OK. */ if (start == single_input) { char *cur = tok->cur; char c = *tok->cur; for (;;) { while (c == ' ' || c == '\t' || c == '\n' || c == '\014') c = *++cur; if (!c) break; if (c != '#') { err_ret->error = E_BADSINGLE; PyNode_Free(n); n = NULL; break; } /* Suck up comment. */ while (c && c != '\n') c = *++cur; } } #endif } else n = NULL; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD *flags = ps->p_flags; #endif PyParser_Delete(ps); if (n == NULL) { if (tok->done == E_EOF) err_ret->error = E_EOF; err_ret->lineno = tok->lineno; if (tok->buf != NULL) { size_t len; assert(tok->cur - tok->buf < INT_MAX); err_ret->offset = (int)(tok->cur - tok->buf); len = tok->inp - tok->buf; err_ret->text = (char *) PyObject_MALLOC(len + 1); if (err_ret->text != NULL) { if (len > 0) strncpy(err_ret->text, tok->buf, len); err_ret->text[len] = '\0'; } } } else if (tok->encoding != NULL) { /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was * allocated using PyMem_ */ node* r = PyNode_New(encoding_decl); if (r) r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1); if (!r || !r->n_str) { err_ret->error = E_NOMEM; if (r) PyObject_FREE(r); n = NULL; goto done; } strcpy(r->n_str, tok->encoding); PyMem_FREE(tok->encoding); tok->encoding = NULL; r->n_nchildren = 1; r->n_child = n; n = r; } done: PyTokenizer_Free(tok); return n; } static int initerr(perrdetail *err_ret, PyObject *filename) { err_ret->error = E_OK; err_ret->lineno = 0; err_ret->offset = 0; err_ret->text = NULL; err_ret->token = -1; err_ret->expected = -1; #ifndef PGEN if (filename) { Py_INCREF(filename); err_ret->filename = filename; } else { err_ret->filename = PyUnicode_FromString("<string>"); if (err_ret->filename == NULL) { err_ret->error = E_ERROR; return -1; } } #endif return 0; }
11,871
389
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/parser.h
#ifndef Py_PARSER_H #define Py_PARSER_H #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/node.h" COSMOPOLITAN_C_START_ /* clang-format off */ #define MAXSTACK 1500 typedef struct { int s_state; /* State in current DFA */ dfa *s_dfa; /* Current DFA */ struct _node *s_parent; /* Where to add next node */ } stackentry; typedef struct { stackentry *s_top; /* Top entry */ stackentry s_base[MAXSTACK];/* Array of stack entries */ /* NB The stack grows down */ } stack; typedef struct { stack p_stack; /* Stack of parser states */ grammar *p_grammar; /* Grammar to use */ node *p_tree; /* Top of parse tree */ #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD unsigned long p_flags; /* see co_flags in Include/code.h */ #endif } parser_state; parser_state *PyParser_New(grammar *g, int start); void PyParser_Delete(parser_state *ps); int PyParser_AddToken(parser_state *ps, int type, char *str, int lineno, int col_offset, int *expected_ret); COSMOPOLITAN_C_END_ #endif /* !Py_PARSER_H */
1,064
38
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/tokenizer_pgen.c
#define PGEN #include "third_party/python/Parser/tokenizer.c"
62
3
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/parsetok_pgen.c
#define PGEN #include "third_party/python/Parser/parsetok.c"
61
3
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/asdl.py
#------------------------------------------------------------------------------- # Parser for ASDL [1] definition files. Reads in an ASDL description and parses # it into an AST that describes it. # # The EBNF we're parsing here: Figure 1 of the paper [1]. Extended to support # modules and attributes after a product. Words starting with Capital letters # are terminals. Literal tokens are in "double quotes". Others are # non-terminals. Id is either TokenId or ConstructorId. # # module ::= "module" Id "{" [definitions] "}" # definitions ::= { TypeId "=" type } # type ::= product | sum # product ::= fields ["attributes" fields] # fields ::= "(" { field, "," } field ")" # field ::= TypeId ["?" | "*"] [Id] # sum ::= constructor { "|" constructor } ["attributes" fields] # constructor ::= ConstructorId [fields] # # [1] "The Zephyr Abstract Syntax Description Language" by Wang, et. al. See # http://asdl.sourceforge.net/ #------------------------------------------------------------------------------- from collections import namedtuple import re __all__ = [ 'builtin_types', 'parse', 'AST', 'Module', 'Type', 'Constructor', 'Field', 'Sum', 'Product', 'VisitorBase', 'Check', 'check'] # The following classes define nodes into which the ASDL description is parsed. # Note: this is a "meta-AST". ASDL files (such as Python.asdl) describe the AST # structure used by a programming language. But ASDL files themselves need to be # parsed. This module parses ASDL files and uses a simple AST to represent them. # See the EBNF at the top of the file to understand the logical connection # between the various node types. builtin_types = {'identifier', 'string', 'bytes', 'int', 'object', 'singleton', 'constant'} class AST: def __repr__(self): raise NotImplementedError class Module(AST): def __init__(self, name, dfns): self.name = name self.dfns = dfns self.types = {type.name: type.value for type in dfns} def __repr__(self): return 'Module({0.name}, {0.dfns})'.format(self) class Type(AST): def __init__(self, name, value): self.name = name self.value = value def __repr__(self): return 'Type({0.name}, {0.value})'.format(self) class Constructor(AST): def __init__(self, name, fields=None): self.name = name self.fields = fields or [] def __repr__(self): return 'Constructor({0.name}, {0.fields})'.format(self) class Field(AST): def __init__(self, type, name=None, seq=False, opt=False): self.type = type self.name = name self.seq = seq self.opt = opt def __repr__(self): if self.seq: extra = ", seq=True" elif self.opt: extra = ", opt=True" else: extra = "" if self.name is None: return 'Field({0.type}{1})'.format(self, extra) else: return 'Field({0.type}, {0.name}{1})'.format(self, extra) class Sum(AST): def __init__(self, types, attributes=None): self.types = types self.attributes = attributes or [] def __repr__(self): if self.attributes: return 'Sum({0.types}, {0.attributes})'.format(self) else: return 'Sum({0.types})'.format(self) class Product(AST): def __init__(self, fields, attributes=None): self.fields = fields self.attributes = attributes or [] def __repr__(self): if self.attributes: return 'Product({0.fields}, {0.attributes})'.format(self) else: return 'Product({0.fields})'.format(self) # A generic visitor for the meta-AST that describes ASDL. This can be used by # emitters. Note that this visitor does not provide a generic visit method, so a # subclass needs to define visit methods from visitModule to as deep as the # interesting node. # We also define a Check visitor that makes sure the parsed ASDL is well-formed. class VisitorBase(object): """Generic tree visitor for ASTs.""" def __init__(self): self.cache = {} def visit(self, obj, *args): klass = obj.__class__ meth = self.cache.get(klass) if meth is None: methname = "visit" + klass.__name__ meth = getattr(self, methname, None) self.cache[klass] = meth if meth: try: meth(obj, *args) except Exception as e: print("Error visiting %r: %s" % (obj, e)) raise class Check(VisitorBase): """A visitor that checks a parsed ASDL tree for correctness. Errors are printed and accumulated. """ def __init__(self): super(Check, self).__init__() self.cons = {} self.errors = 0 self.types = {} def visitModule(self, mod): for dfn in mod.dfns: self.visit(dfn) def visitType(self, type): self.visit(type.value, str(type.name)) def visitSum(self, sum, name): for t in sum.types: self.visit(t, name) def visitConstructor(self, cons, name): key = str(cons.name) conflict = self.cons.get(key) if conflict is None: self.cons[key] = name else: print('Redefinition of constructor {}'.format(key)) print('Defined in {} and {}'.format(conflict, name)) self.errors += 1 for f in cons.fields: self.visit(f, key) def visitField(self, field, name): key = str(field.type) l = self.types.setdefault(key, []) l.append(name) def visitProduct(self, prod, name): for f in prod.fields: self.visit(f, name) def check(mod): """Check the parsed ASDL tree for correctness. Return True if success. For failure, the errors are printed out and False is returned. """ v = Check() v.visit(mod) for t in v.types: if t not in mod.types and not t in builtin_types: v.errors += 1 uses = ", ".join(v.types[t]) print('Undefined type {}, used in {}'.format(t, uses)) return not v.errors # The ASDL parser itself comes next. The only interesting external interface # here is the top-level parse function. def parse(filename): """Parse ASDL from the given file and return a Module node describing it.""" with open(filename) as f: parser = ASDLParser() return parser.parse(f.read()) # Types for describing tokens in an ASDL specification. class TokenKind: """TokenKind is provides a scope for enumerated token kinds.""" (ConstructorId, TypeId, Equals, Comma, Question, Pipe, Asterisk, LParen, RParen, LBrace, RBrace) = range(11) operator_table = { '=': Equals, ',': Comma, '?': Question, '|': Pipe, '(': LParen, ')': RParen, '*': Asterisk, '{': LBrace, '}': RBrace} Token = namedtuple('Token', 'kind value lineno') class ASDLSyntaxError(Exception): def __init__(self, msg, lineno=None): self.msg = msg self.lineno = lineno or '<unknown>' def __str__(self): return 'Syntax error on line {0.lineno}: {0.msg}'.format(self) def tokenize_asdl(buf): """Tokenize the given buffer. Yield Token objects.""" for lineno, line in enumerate(buf.splitlines(), 1): for m in re.finditer(r'\s*(\w+|--.*|.)', line.strip()): c = m.group(1) if c[0].isalpha(): # Some kind of identifier if c[0].isupper(): yield Token(TokenKind.ConstructorId, c, lineno) else: yield Token(TokenKind.TypeId, c, lineno) elif c[:2] == '--': # Comment break else: # Operators try: op_kind = TokenKind.operator_table[c] except KeyError: raise ASDLSyntaxError('Invalid operator %s' % c, lineno) yield Token(op_kind, c, lineno) class ASDLParser: """Parser for ASDL files. Create, then call the parse method on a buffer containing ASDL. This is a simple recursive descent parser that uses tokenize_asdl for the lexing. """ def __init__(self): self._tokenizer = None self.cur_token = None def parse(self, buf): """Parse the ASDL in the buffer and return an AST with a Module root. """ self._tokenizer = tokenize_asdl(buf) self._advance() return self._parse_module() def _parse_module(self): if self._at_keyword('module'): self._advance() else: raise ASDLSyntaxError( 'Expected "module" (found {})'.format(self.cur_token.value), self.cur_token.lineno) name = self._match(self._id_kinds) self._match(TokenKind.LBrace) defs = self._parse_definitions() self._match(TokenKind.RBrace) return Module(name, defs) def _parse_definitions(self): defs = [] while self.cur_token.kind == TokenKind.TypeId: typename = self._advance() self._match(TokenKind.Equals) type = self._parse_type() defs.append(Type(typename, type)) return defs def _parse_type(self): if self.cur_token.kind == TokenKind.LParen: # If we see a (, it's a product return self._parse_product() else: # Otherwise it's a sum. Look for ConstructorId sumlist = [Constructor(self._match(TokenKind.ConstructorId), self._parse_optional_fields())] while self.cur_token.kind == TokenKind.Pipe: # More constructors self._advance() sumlist.append(Constructor( self._match(TokenKind.ConstructorId), self._parse_optional_fields())) return Sum(sumlist, self._parse_optional_attributes()) def _parse_product(self): return Product(self._parse_fields(), self._parse_optional_attributes()) def _parse_fields(self): fields = [] self._match(TokenKind.LParen) while self.cur_token.kind == TokenKind.TypeId: typename = self._advance() is_seq, is_opt = self._parse_optional_field_quantifier() id = (self._advance() if self.cur_token.kind in self._id_kinds else None) fields.append(Field(typename, id, seq=is_seq, opt=is_opt)) if self.cur_token.kind == TokenKind.RParen: break elif self.cur_token.kind == TokenKind.Comma: self._advance() self._match(TokenKind.RParen) return fields def _parse_optional_fields(self): if self.cur_token.kind == TokenKind.LParen: return self._parse_fields() else: return None def _parse_optional_attributes(self): if self._at_keyword('attributes'): self._advance() return self._parse_fields() else: return None def _parse_optional_field_quantifier(self): is_seq, is_opt = False, False if self.cur_token.kind == TokenKind.Asterisk: is_seq = True self._advance() elif self.cur_token.kind == TokenKind.Question: is_opt = True self._advance() return is_seq, is_opt def _advance(self): """ Return the value of the current token and read the next one into self.cur_token. """ cur_val = None if self.cur_token is None else self.cur_token.value try: self.cur_token = next(self._tokenizer) except StopIteration: self.cur_token = None return cur_val _id_kinds = (TokenKind.ConstructorId, TokenKind.TypeId) def _match(self, kind): """The 'match' primitive of RD parsers. * Verifies that the current token is of the given kind (kind can be a tuple, in which the kind must match one of its members). * Returns the value of the current token * Reads in the next token """ if (isinstance(kind, tuple) and self.cur_token.kind in kind or self.cur_token.kind == kind ): value = self.cur_token.value self._advance() return value else: raise ASDLSyntaxError( 'Unmatched {} (found {})'.format(kind, self.cur_token.kind), self.cur_token.lineno) def _at_keyword(self, keyword): return (self.cur_token.kind == TokenKind.TypeId and self.cur_token.value == keyword)
12,881
377
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/firstsets.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/bitset.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Include/token.h" /* clang-format off */ extern int Py_DebugFlag; /* Forward */ static void calcfirstset(grammar *, dfa *); void addfirstsets(grammar *g) { int i; dfa *d; if (Py_DebugFlag) printf("Adding FIRST sets ...\n"); for (i = 0; i < g->g_ndfas; i++) { d = &g->g_dfa[i]; if (d->d_first == NULL) calcfirstset(g, d); } } static void calcfirstset(grammar *g, dfa *d) { int i, j; state *s; arc *a; int nsyms; int *sym; int nbits; static bitset dummy; bitset result; int type; dfa *d1; label *l0; if (Py_DebugFlag) printf("Calculate FIRST set for '%s'\n", d->d_name); if (dummy == NULL) dummy = newbitset(1); if (d->d_first == dummy) { fprintf(stderr, "Left-recursion for '%s'\n", d->d_name); return; } if (d->d_first != NULL) { fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n", d->d_name); } d->d_first = dummy; l0 = g->g_ll.ll_label; nbits = g->g_ll.ll_nlabels; result = newbitset(nbits); sym = (int *)PyObject_MALLOC(sizeof(int)); if (sym == NULL) Py_FatalError("no mem for new sym in calcfirstset"); nsyms = 1; sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL); s = &d->d_state[d->d_initial]; for (i = 0; i < s->s_narcs; i++) { a = &s->s_arc[i]; for (j = 0; j < nsyms; j++) { if (sym[j] == a->a_lbl) break; } if (j >= nsyms) { /* New label */ sym = (int *)PyObject_REALLOC(sym, sizeof(int) * (nsyms + 1)); if (sym == NULL) Py_FatalError( "no mem to resize sym in calcfirstset"); sym[nsyms++] = a->a_lbl; type = l0[a->a_lbl].lb_type; if (ISNONTERMINAL(type)) { d1 = PyGrammar_FindDFA(g, type); if (d1->d_first == dummy) { fprintf(stderr, "Left-recursion below '%s'\n", d->d_name); } else { if (d1->d_first == NULL) calcfirstset(g, d1); mergebitset(result, d1->d_first, nbits); } } else if (ISTERMINAL(type)) { addbit(result, a->a_lbl); } } } d->d_first = result; if (Py_DebugFlag) { printf("FIRST set for '%s': {", d->d_name); for (i = 0; i < nbits; i++) { if (testbit(result, i)) printf(" %s", PyGrammar_LabelRepr(&l0[i])); } printf(" }\n"); } PyObject_FREE(sym); }
3,834
120
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/tokenizer.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "third_party/python/Include/errcode.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Parser/tokenizer.h" #ifndef PGEN #include "libc/calls/weirdtypes.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/unicodeobject.h" #endif /* clang-format off */ /* Tokenizer implementation */ #define is_potential_identifier_start(c) (\ (c >= 'a' && c <= 'z')\ || (c >= 'A' && c <= 'Z')\ || c == '_'\ || (c >= 128)) #define is_potential_identifier_char(c) (\ (c >= 'a' && c <= 'z')\ || (c >= 'A' && c <= 'Z')\ || (c >= '0' && c <= '9')\ || c == '_'\ || (c >= 128)) extern char *PyOS_Readline(FILE *, FILE *, const char *); /* Return malloc'ed string including trailing \n; empty malloc'ed string for EOF; NULL if interrupted */ /* Don't ever change this -- it would break the portability of Python code */ #define TABSIZE 8 /* Forward */ static struct tok_state *tok_new(void); static int tok_nextc(struct tok_state *tok); static void tok_backup(struct tok_state *tok, int c); /* Token names */ const char *_PyParser_TokenNames[] = { "ENDMARKER", "NAME", "NUMBER", "STRING", "NEWLINE", "INDENT", "DEDENT", "LPAR", "RPAR", "LSQB", "RSQB", "COLON", "COMMA", "SEMI", "PLUS", "MINUS", "STAR", "SLASH", "VBAR", "AMPER", "LESS", "GREATER", "EQUAL", "DOT", "PERCENT", "LBRACE", "RBRACE", "EQEQUAL", "NOTEQUAL", "LESSEQUAL", "GREATEREQUAL", "TILDE", "CIRCUMFLEX", "LEFTSHIFT", "RIGHTSHIFT", "DOUBLESTAR", "PLUSEQUAL", "MINEQUAL", "STAREQUAL", "SLASHEQUAL", "PERCENTEQUAL", "AMPEREQUAL", "VBAREQUAL", "CIRCUMFLEXEQUAL", "LEFTSHIFTEQUAL", "RIGHTSHIFTEQUAL", "DOUBLESTAREQUAL", "DOUBLESLASH", "DOUBLESLASHEQUAL", "AT", "ATEQUAL", "RARROW", "ELLIPSIS", /* This table must match the #defines in token.h! */ "OP", "AWAIT", "ASYNC", "<ERRORTOKEN>", "<N_TOKENS>" }; /* Create and initialize a new tok_state structure */ static struct tok_state * tok_new(void) { struct tok_state *tok = (struct tok_state *)PyMem_MALLOC( sizeof(struct tok_state)); if (tok == NULL) return NULL; tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; tok->done = E_OK; tok->fp = NULL; tok->input = NULL; tok->tabsize = TABSIZE; tok->indent = 0; tok->indstack[0] = 0; tok->atbol = 1; tok->pendin = 0; tok->prompt = tok->nextprompt = NULL; tok->lineno = 0; tok->level = 0; tok->altwarning = 1; tok->alterror = 1; tok->alttabsize = 1; tok->altindstack[0] = 0; tok->decoding_state = STATE_INIT; tok->decoding_erred = 0; tok->read_coding_spec = 0; tok->enc = NULL; tok->encoding = NULL; tok->cont_line = 0; #ifndef PGEN tok->filename = NULL; tok->decoding_readline = NULL; tok->decoding_buffer = NULL; #endif tok->async_def = 0; tok->async_def_indent = 0; tok->async_def_nl = 0; return tok; } static char * new_string(const char *s, Py_ssize_t len, struct tok_state *tok) { char* result = (char *)PyMem_MALLOC(len + 1); if (!result) { tok->done = E_NOMEM; return NULL; } memcpy(result, s, len); result[len] = '\0'; return result; } #ifdef PGEN static char * decoding_fgets(char *s, int size, struct tok_state *tok) { return fgets(s, size, tok->fp); } static int decoding_feof(struct tok_state *tok) { return feof(tok->fp); } static char * decode_str(const char *str, int exec_input, struct tok_state *tok) { return new_string(str, strlen(str), tok); } #else /* PGEN */ static char * error_ret(struct tok_state *tok) /* XXX */ { tok->decoding_erred = 1; if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */ PyMem_FREE(tok->buf); tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL; tok->done = E_DECODE; return NULL; /* as if it were EOF */ } static const char * get_normal_name(const char *s) /* for utf-8 and latin-1 */ { char buf[13]; int i; for (i = 0; i < 12; i++) { int c = s[i]; if (c == '\0') break; else if (c == '_') buf[i] = '-'; else buf[i] = tolower(c); } buf[i] = '\0'; if (strcmp(buf, "utf-8") == 0 || strncmp(buf, "utf-8-", 6) == 0) return "utf-8"; else if (strcmp(buf, "latin-1") == 0 || strcmp(buf, "iso-8859-1") == 0 || strcmp(buf, "iso-latin-1") == 0 || strncmp(buf, "latin-1-", 8) == 0 || strncmp(buf, "iso-8859-1-", 11) == 0 || strncmp(buf, "iso-latin-1-", 12) == 0) return "iso-8859-1"; else return s; } /* Return the coding spec in S, or NULL if none is found. */ static int get_coding_spec(const char *s, char **spec, Py_ssize_t size, struct tok_state *tok) { Py_ssize_t i; *spec = NULL; /* Coding spec must be in a comment, and that comment must be * the only statement on the source code line. */ for (i = 0; i < size - 6; i++) { if (s[i] == '#') break; if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014') return 1; } for (; i < size - 6; i++) { /* XXX inefficient search */ const char* t = s + i; if (strncmp(t, "coding", 6) == 0) { const char* begin = NULL; t += 6; if (t[0] != ':' && t[0] != '=') continue; do { t++; } while (t[0] == '\x20' || t[0] == '\t'); begin = t; while (Py_ISALNUM(t[0]) || t[0] == '-' || t[0] == '_' || t[0] == '.') t++; if (begin < t) { char* r = new_string(begin, t - begin, tok); const char* q; if (!r) return 0; q = get_normal_name(r); if (r != q) { PyMem_FREE(r); r = new_string(q, strlen(q), tok); if (!r) return 0; } *spec = r; break; } } } return 1; } /* Check whether the line contains a coding spec. If it does, invoke the set_readline function for the new encoding. This function receives the tok_state and the new encoding. Return 1 on success, 0 on failure. */ static int check_coding_spec(const char* line, Py_ssize_t size, struct tok_state *tok, int set_readline(struct tok_state *, const char *)) { char *cs; int r = 1; if (tok->cont_line) { /* It's a continuation line, so it can't be a coding spec. */ tok->read_coding_spec = 1; return 1; } if (!get_coding_spec(line, &cs, size, tok)) return 0; if (!cs) { Py_ssize_t i; for (i = 0; i < size; i++) { if (line[i] == '#' || line[i] == '\n' || line[i] == '\r') break; if (line[i] != ' ' && line[i] != '\t' && line[i] != '\014') { /* Stop checking coding spec after a line containing * anything except a comment. */ tok->read_coding_spec = 1; break; } } return 1; } tok->read_coding_spec = 1; if (tok->encoding == NULL) { assert(tok->decoding_state == STATE_RAW); if (strcmp(cs, "utf-8") == 0) { tok->encoding = cs; } else { r = set_readline(tok, cs); if (r) { tok->encoding = cs; tok->decoding_state = STATE_NORMAL; } else { PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs); PyMem_FREE(cs); } } } else { /* then, compare cs with BOM */ r = (strcmp(tok->encoding, cs) == 0); if (!r) PyErr_Format(PyExc_SyntaxError, "encoding problem: %s with BOM", cs); PyMem_FREE(cs); } return r; } /* See whether the file starts with a BOM. If it does, invoke the set_readline function with the new encoding. Return 1 on success, 0 on failure. */ static int check_bom(int get_char(struct tok_state *), void unget_char(int, struct tok_state *), int set_readline(struct tok_state *, const char *), struct tok_state *tok) { int ch1, ch2, ch3; ch1 = get_char(tok); tok->decoding_state = STATE_RAW; if (ch1 == EOF) { return 1; } else if (ch1 == 0xEF) { ch2 = get_char(tok); if (ch2 != 0xBB) { unget_char(ch2, tok); unget_char(ch1, tok); return 1; } ch3 = get_char(tok); if (ch3 != 0xBF) { unget_char(ch3, tok); unget_char(ch2, tok); unget_char(ch1, tok); return 1; } #if 0 /* Disable support for UTF-16 BOMs until a decision is made whether this needs to be supported. */ } else if (ch1 == 0xFE) { ch2 = get_char(tok); if (ch2 != 0xFF) { unget_char(ch2, tok); unget_char(ch1, tok); return 1; } if (!set_readline(tok, "utf-16-be")) return 0; tok->decoding_state = STATE_NORMAL; } else if (ch1 == 0xFF) { ch2 = get_char(tok); if (ch2 != 0xFE) { unget_char(ch2, tok); unget_char(ch1, tok); return 1; } if (!set_readline(tok, "utf-16-le")) return 0; tok->decoding_state = STATE_NORMAL; #endif } else { unget_char(ch1, tok); return 1; } if (tok->encoding != NULL) PyMem_FREE(tok->encoding); tok->encoding = new_string("utf-8", 5, tok); if (!tok->encoding) return 0; /* No need to set_readline: input is already utf-8 */ return 1; } /* Read a line of text from TOK into S, using the stream in TOK. Return NULL on failure, else S. On entry, tok->decoding_buffer will be one of: 1) NULL: need to call tok->decoding_readline to get a new line 2) PyUnicodeObject *: decoding_feof has called tok->decoding_readline and stored the result in tok->decoding_buffer 3) PyByteArrayObject *: previous call to fp_readl did not have enough room (in the s buffer) to copy entire contents of the line read by tok->decoding_readline. tok->decoding_buffer has the overflow. In this case, fp_readl is called in a loop (with an expanded buffer) until the buffer ends with a '\n' (or until the end of the file is reached): see tok_nextc and its calls to decoding_fgets. */ static char * fp_readl(char *s, int size, struct tok_state *tok) { PyObject* bufobj; const char *buf; Py_ssize_t buflen; /* Ask for one less byte so we can terminate it */ assert(size > 0); size--; if (tok->decoding_buffer) { bufobj = tok->decoding_buffer; Py_INCREF(bufobj); } else { bufobj = PyObject_CallObject(tok->decoding_readline, NULL); if (bufobj == NULL) goto error; } if (PyUnicode_CheckExact(bufobj)) { buf = PyUnicode_AsUTF8AndSize(bufobj, &buflen); if (buf == NULL) { goto error; } } else { buf = PyByteArray_AsString(bufobj); if (buf == NULL) { goto error; } buflen = PyByteArray_GET_SIZE(bufobj); } Py_XDECREF(tok->decoding_buffer); if (buflen > size) { /* Too many chars, the rest goes into tok->decoding_buffer */ tok->decoding_buffer = PyByteArray_FromStringAndSize(buf+size, buflen-size); if (tok->decoding_buffer == NULL) goto error; buflen = size; } else tok->decoding_buffer = NULL; memcpy(s, buf, buflen); s[buflen] = '\0'; if (buflen == 0) /* EOF */ s = NULL; Py_DECREF(bufobj); return s; error: Py_XDECREF(bufobj); return error_ret(tok); } /* Set the readline function for TOK to a StreamReader's readline function. The StreamReader is named ENC. This function is called from check_bom and check_coding_spec. ENC is usually identical to the future value of tok->encoding, except for the (currently unsupported) case of UTF-16. Return 1 on success, 0 on failure. */ static int fp_setreadl(struct tok_state *tok, const char* enc) { PyObject *readline, *io, *stream; _Py_IDENTIFIER(open); _Py_IDENTIFIER(readline); int fd; long pos; fd = fileno(tok->fp); /* Due to buffering the file offset for fd can be different from the file * position of tok->fp. If tok->fp was opened in text mode on Windows, * its file position counts CRLF as one char and can't be directly mapped * to the file offset for fd. Instead we step back one byte and read to * the end of line.*/ pos = ftell(tok->fp); if (pos == -1 || lseek(fd, (off_t)(pos > 0 ? pos - 1 : pos), SEEK_SET) == (off_t)-1) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, NULL); return 0; } io = PyImport_ImportModuleNoBlock("io"); if (io == NULL) return 0; stream = _PyObject_CallMethodId(io, &PyId_open, "isisOOO", fd, "r", -1, enc, Py_None, Py_None, Py_False); Py_DECREF(io); if (stream == NULL) return 0; readline = _PyObject_GetAttrId(stream, &PyId_readline); Py_DECREF(stream); if (readline == NULL) return 0; Py_XSETREF(tok->decoding_readline, readline); if (pos > 0) { PyObject *bufobj = PyObject_CallObject(readline, NULL); if (bufobj == NULL) return 0; Py_DECREF(bufobj); } return 1; } /* Fetch the next byte from TOK. */ static int fp_getc(struct tok_state *tok) { return getc(tok->fp); } /* Unfetch the last byte back into TOK. */ static void fp_ungetc(int c, struct tok_state *tok) { ungetc(c, tok->fp); } /* Check whether the characters at s start a valid UTF-8 sequence. Return the number of characters forming the sequence if yes, 0 if not. */ static int valid_utf8(const unsigned char* s) { int expected = 0; int length; if (*s < 0x80) /* single-byte code */ return 1; if (*s < 0xc0) /* following byte */ return 0; if (*s < 0xE0) expected = 1; else if (*s < 0xF0) expected = 2; else if (*s < 0xF8) expected = 3; else return 0; length = expected + 1; for (; expected; expected--) if (s[expected] < 0x80 || s[expected] >= 0xC0) return 0; return length; } /* Read a line of input from TOK. Determine encoding if necessary. */ static char * decoding_fgets(char *s, int size, struct tok_state *tok) { char *line = NULL; int badchar = 0; for (;;) { if (tok->decoding_state == STATE_NORMAL) { /* We already have a codec associated with this input. */ line = fp_readl(s, size, tok); break; } else if (tok->decoding_state == STATE_RAW) { /* We want a 'raw' read. */ line = Py_UniversalNewlineFgets(s, size, tok->fp, NULL); break; } else { /* We have not yet determined the encoding. If an encoding is found, use the file-pointer reader functions from now on. */ if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok)) return error_ret(tok); assert(tok->decoding_state != STATE_INIT); } } if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) { if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) { return error_ret(tok); } } #ifndef PGEN /* The default encoding is UTF-8, so make sure we don't have any non-UTF-8 sequences in it. */ if (line && !tok->encoding) { unsigned char *c; int length; for (c = (unsigned char *)line; *c; c += length) if (!(length = valid_utf8(c))) { badchar = *c; break; } } if (badchar) { /* Need to add 1 to the line number, since this line has not been counted, yet. */ PyErr_Format(PyExc_SyntaxError, "Non-UTF-8 code starting with '\\x%.2x' " "in file %U on line %i, " "but no encoding declared; " "see http://python.org/dev/peps/pep-0263/ for details", badchar, tok->filename, tok->lineno + 1); return error_ret(tok); } #endif return line; } static int decoding_feof(struct tok_state *tok) { if (tok->decoding_state != STATE_NORMAL) { return feof(tok->fp); } else { PyObject* buf = tok->decoding_buffer; if (buf == NULL) { buf = PyObject_CallObject(tok->decoding_readline, NULL); if (buf == NULL) { error_ret(tok); return 1; } else { tok->decoding_buffer = buf; } } return PyObject_Length(buf) == 0; } } /* Fetch a byte from TOK, using the string buffer. */ static int buf_getc(struct tok_state *tok) { return Py_CHARMASK(*tok->str++); } /* Unfetch a byte from TOK, using the string buffer. */ static void buf_ungetc(int c, struct tok_state *tok) { tok->str--; assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */ } /* Set the readline function for TOK to ENC. For the string-based tokenizer, this means to just record the encoding. */ static int buf_setreadl(struct tok_state *tok, const char* enc) { tok->enc = enc; return 1; } /* Return a UTF-8 encoding Python string object from the C byte string STR, which is encoded with ENC. */ static PyObject * translate_into_utf8(const char* str, const char* enc) { PyObject *utf8; PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL); if (buf == NULL) return NULL; utf8 = PyUnicode_AsUTF8String(buf); Py_DECREF(buf); return utf8; } static char * translate_newlines(const char *s, int exec_input, struct tok_state *tok) { int skip_next_lf = 0; size_t needed_length = strlen(s) + 2, final_length; char *buf, *current; char c = '\0'; buf = PyMem_MALLOC(needed_length); if (buf == NULL) { tok->done = E_NOMEM; return NULL; } for (current = buf; *s; s++, current++) { c = *s; if (skip_next_lf) { skip_next_lf = 0; if (c == '\n') { c = *++s; if (!c) break; } } if (c == '\r') { skip_next_lf = 1; c = '\n'; } *current = c; } /* If this is exec input, add a newline to the end of the string if there isn't one already. */ if (exec_input && c != '\n') { *current = '\n'; current++; } *current = '\0'; final_length = current - buf + 1; if (final_length < needed_length && final_length) /* should never fail */ buf = PyMem_REALLOC(buf, final_length); return buf; } /* Decode a byte string STR for use as the buffer of TOK. Look for encoding declarations inside STR, and record them inside TOK. */ static const char * decode_str(const char *input, int single, struct tok_state *tok) { PyObject* utf8 = NULL; const char *str; const char *s; const char *newl[2] = {NULL, NULL}; int lineno = 0; tok->input = str = translate_newlines(input, single, tok); if (str == NULL) return NULL; tok->enc = NULL; tok->str = str; if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok)) return error_ret(tok); str = tok->str; /* string after BOM if any */ assert(str); if (tok->enc != NULL) { utf8 = translate_into_utf8(str, tok->enc); if (utf8 == NULL) return error_ret(tok); str = PyBytes_AsString(utf8); } for (s = str;; s++) { if (*s == '\0') break; else if (*s == '\n') { assert(lineno < 2); newl[lineno] = s; lineno++; if (lineno == 2) break; } } tok->enc = NULL; /* need to check line 1 and 2 separately since check_coding_spec assumes a single line as input */ if (newl[0]) { if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl)) return error_ret(tok); if (tok->enc == NULL && !tok->read_coding_spec && newl[1]) { if (!check_coding_spec(newl[0]+1, newl[1] - newl[0], tok, buf_setreadl)) return error_ret(tok); } } if (tok->enc != NULL) { assert(utf8 == NULL); utf8 = translate_into_utf8(str, tok->enc); if (utf8 == NULL) return error_ret(tok); str = PyBytes_AS_STRING(utf8); } assert(tok->decoding_buffer == NULL); tok->decoding_buffer = utf8; /* CAUTION */ return str; } #endif /* PGEN */ /* Set up tokenizer for string */ struct tok_state * PyTokenizer_FromString(const char *str, int exec_input) { struct tok_state *tok = tok_new(); if (tok == NULL) return NULL; str = decode_str(str, exec_input, tok); if (str == NULL) { PyTokenizer_Free(tok); return NULL; } /* XXX: constify members. */ tok->buf = tok->cur = tok->end = tok->inp = (char*)str; return tok; } struct tok_state * PyTokenizer_FromUTF8(const char *str, int exec_input) { struct tok_state *tok = tok_new(); if (tok == NULL) return NULL; #ifndef PGEN tok->input = str = translate_newlines(str, exec_input, tok); #endif if (str == NULL) { PyTokenizer_Free(tok); return NULL; } tok->decoding_state = STATE_RAW; tok->read_coding_spec = 1; tok->enc = NULL; tok->str = str; tok->encoding = (char *)PyMem_MALLOC(6); if (!tok->encoding) { PyTokenizer_Free(tok); return NULL; } strcpy(tok->encoding, "utf-8"); /* XXX: constify members. */ tok->buf = tok->cur = tok->end = tok->inp = (char*)str; return tok; } /* Set up tokenizer for file */ struct tok_state * PyTokenizer_FromFile(FILE *fp, const char* enc, const char *ps1, const char *ps2) { struct tok_state *tok = tok_new(); if (tok == NULL) return NULL; if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) { PyTokenizer_Free(tok); return NULL; } tok->cur = tok->inp = tok->buf; tok->end = tok->buf + BUFSIZ; tok->fp = fp; tok->prompt = ps1; tok->nextprompt = ps2; if (enc != NULL) { /* Must copy encoding declaration since it gets copied into the parse tree. */ tok->encoding = PyMem_MALLOC(strlen(enc)+1); if (!tok->encoding) { PyTokenizer_Free(tok); return NULL; } strcpy(tok->encoding, enc); tok->decoding_state = STATE_NORMAL; } return tok; } /* Free a tok_state structure */ void PyTokenizer_Free(struct tok_state *tok) { if (tok->encoding != NULL) PyMem_FREE(tok->encoding); #ifndef PGEN Py_XDECREF(tok->decoding_readline); Py_XDECREF(tok->decoding_buffer); Py_XDECREF(tok->filename); #endif if (tok->fp != NULL && tok->buf != NULL) PyMem_FREE(tok->buf); if (tok->input) PyMem_FREE((char *)tok->input); PyMem_FREE(tok); } /* Get next char, updating state; error code goes into tok->done */ static int tok_nextc(struct tok_state *tok) { for (;;) { if (tok->cur != tok->inp) { return Py_CHARMASK(*tok->cur++); /* Fast path */ } if (tok->done != E_OK) return EOF; if (tok->fp == NULL) { char *end = strchr(tok->inp, '\n'); if (end != NULL) end++; else { end = strchr(tok->inp, '\0'); if (end == tok->inp) { tok->done = E_EOF; return EOF; } } if (tok->start == NULL) tok->buf = tok->cur; tok->line_start = tok->cur; tok->lineno++; tok->inp = end; return Py_CHARMASK(*tok->cur++); } if (tok->prompt != NULL) { char *newtok = PyOS_Readline(stdin, stdout, tok->prompt); #ifndef PGEN if (newtok != NULL) { char *translated = translate_newlines(newtok, 0, tok); PyMem_FREE(newtok); if (translated == NULL) return EOF; newtok = translated; } if (tok->encoding && newtok && *newtok) { /* Recode to UTF-8 */ Py_ssize_t buflen; const char* buf; PyObject *u = translate_into_utf8(newtok, tok->encoding); PyMem_FREE(newtok); if (!u) { tok->done = E_DECODE; return EOF; } buflen = PyBytes_GET_SIZE(u); buf = PyBytes_AS_STRING(u); newtok = PyMem_MALLOC(buflen+1); if (newtok == NULL) { Py_DECREF(u); tok->done = E_NOMEM; return EOF; } strcpy(newtok, buf); Py_DECREF(u); } #endif if (tok->nextprompt != NULL) tok->prompt = tok->nextprompt; if (newtok == NULL) tok->done = E_INTR; else if (*newtok == '\0') { PyMem_FREE(newtok); tok->done = E_EOF; } else if (tok->start != NULL) { size_t start = tok->start - tok->buf; size_t oldlen = tok->cur - tok->buf; size_t newlen = oldlen + strlen(newtok); char *buf = tok->buf; buf = (char *)PyMem_REALLOC(buf, newlen+1); tok->lineno++; if (buf == NULL) { PyMem_FREE(tok->buf); tok->buf = NULL; PyMem_FREE(newtok); tok->done = E_NOMEM; return EOF; } tok->buf = buf; tok->cur = tok->buf + oldlen; tok->line_start = tok->cur; strcpy(tok->buf + oldlen, newtok); PyMem_FREE(newtok); tok->inp = tok->buf + newlen; tok->end = tok->inp + 1; tok->start = tok->buf + start; } else { tok->lineno++; if (tok->buf != NULL) PyMem_FREE(tok->buf); tok->buf = newtok; tok->cur = tok->buf; tok->line_start = tok->buf; tok->inp = strchr(tok->buf, '\0'); tok->end = tok->inp + 1; } } else { int done = 0; Py_ssize_t cur = 0; char *pt; if (tok->start == NULL) { if (tok->buf == NULL) { tok->buf = (char *) PyMem_MALLOC(BUFSIZ); if (tok->buf == NULL) { tok->done = E_NOMEM; return EOF; } tok->end = tok->buf + BUFSIZ; } if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf), tok) == NULL) { if (!tok->decoding_erred) tok->done = E_EOF; done = 1; } else { tok->done = E_OK; tok->inp = strchr(tok->buf, '\0'); done = tok->inp == tok->buf || tok->inp[-1] == '\n'; } } else { cur = tok->cur - tok->buf; if (decoding_feof(tok)) { tok->done = E_EOF; done = 1; } else tok->done = E_OK; } tok->lineno++; /* Read until '\n' or EOF */ while (!done) { Py_ssize_t curstart = tok->start == NULL ? -1 : tok->start - tok->buf; Py_ssize_t curvalid = tok->inp - tok->buf; Py_ssize_t newsize = curvalid + BUFSIZ; char *newbuf = tok->buf; newbuf = (char *)PyMem_REALLOC(newbuf, newsize); if (newbuf == NULL) { tok->done = E_NOMEM; tok->cur = tok->inp; return EOF; } tok->buf = newbuf; tok->cur = tok->buf + cur; tok->line_start = tok->cur; tok->inp = tok->buf + curvalid; tok->end = tok->buf + newsize; tok->start = curstart < 0 ? NULL : tok->buf + curstart; if (decoding_fgets(tok->inp, (int)(tok->end - tok->inp), tok) == NULL) { /* Break out early on decoding errors, as tok->buf will be NULL */ if (tok->decoding_erred) return EOF; /* Last line does not end in \n, fake one */ strcpy(tok->inp, "\n"); } tok->inp = strchr(tok->inp, '\0'); done = tok->inp[-1] == '\n'; } if (tok->buf != NULL) { tok->cur = tok->buf + cur; tok->line_start = tok->cur; /* replace "\r\n" with "\n" */ /* For Mac leave the \r, giving a syntax error */ pt = tok->inp - 2; if (pt >= tok->buf && *pt == '\r') { *pt++ = '\n'; *pt = '\0'; tok->inp = pt; } } } if (tok->done != E_OK) { if (tok->prompt != NULL) PySys_WriteStderr("\n"); tok->cur = tok->inp; return EOF; } } /*NOTREACHED*/ } /* Back-up one character */ static void tok_backup(struct tok_state *tok, int c) { if (c != EOF) { if (--tok->cur < tok->buf) Py_FatalError("tok_backup: beginning of buffer"); if (*tok->cur != c) *tok->cur = c; } } /* Return the token corresponding to a single character */ int PyToken_OneChar(int c) { switch (c) { case '(': return LPAR; case ')': return RPAR; case '[': return LSQB; case ']': return RSQB; case ':': return COLON; case ',': return COMMA; case ';': return SEMI; case '+': return PLUS; case '-': return MINUS; case '*': return STAR; case '/': return SLASH; case '|': return VBAR; case '&': return AMPER; case '<': return LESS; case '>': return GREATER; case '=': return EQUAL; case '.': return DOT; case '%': return PERCENT; case '{': return LBRACE; case '}': return RBRACE; case '^': return CIRCUMFLEX; case '~': return TILDE; case '@': return AT; default: return OP; } } int PyToken_TwoChars(int c1, int c2) { switch (c1) { case '=': switch (c2) { case '=': return EQEQUAL; } break; case '!': switch (c2) { case '=': return NOTEQUAL; } break; case '<': switch (c2) { case '>': return NOTEQUAL; case '=': return LESSEQUAL; case '<': return LEFTSHIFT; } break; case '>': switch (c2) { case '=': return GREATEREQUAL; case '>': return RIGHTSHIFT; } break; case '+': switch (c2) { case '=': return PLUSEQUAL; } break; case '-': switch (c2) { case '=': return MINEQUAL; case '>': return RARROW; } break; case '*': switch (c2) { case '*': return DOUBLESTAR; case '=': return STAREQUAL; } break; case '/': switch (c2) { case '/': return DOUBLESLASH; case '=': return SLASHEQUAL; } break; case '|': switch (c2) { case '=': return VBAREQUAL; } break; case '%': switch (c2) { case '=': return PERCENTEQUAL; } break; case '&': switch (c2) { case '=': return AMPEREQUAL; } break; case '^': switch (c2) { case '=': return CIRCUMFLEXEQUAL; } break; case '@': switch (c2) { case '=': return ATEQUAL; } break; } return OP; } int PyToken_ThreeChars(int c1, int c2, int c3) { switch (c1) { case '<': switch (c2) { case '<': switch (c3) { case '=': return LEFTSHIFTEQUAL; } break; } break; case '>': switch (c2) { case '>': switch (c3) { case '=': return RIGHTSHIFTEQUAL; } break; } break; case '*': switch (c2) { case '*': switch (c3) { case '=': return DOUBLESTAREQUAL; } break; } break; case '/': switch (c2) { case '/': switch (c3) { case '=': return DOUBLESLASHEQUAL; } break; } break; case '.': switch (c2) { case '.': switch (c3) { case '.': return ELLIPSIS; } break; } break; } return OP; } static int indenterror(struct tok_state *tok) { if (tok->alterror) { tok->done = E_TABSPACE; tok->cur = tok->inp; return 1; } if (tok->altwarning) { #ifdef PGEN PySys_WriteStderr("inconsistent use of tabs and spaces " "in indentation\n"); #else PySys_FormatStderr("%U: inconsistent use of tabs and spaces " "in indentation\n", tok->filename); #endif tok->altwarning = 0; } return 0; } #ifdef PGEN #define verify_identifier(tok) 1 #else /* Verify that the identifier follows PEP 3131. All identifier strings are guaranteed to be "ready" unicode objects. */ static int verify_identifier(struct tok_state *tok) { PyObject *s; int result; if (tok->decoding_erred) return 0; s = PyUnicode_DecodeUTF8(tok->start, tok->cur - tok->start, NULL); if (s == NULL || PyUnicode_READY(s) == -1) { if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) { PyErr_Clear(); tok->done = E_IDENTIFIER; } else { tok->done = E_ERROR; } return 0; } result = PyUnicode_IsIdentifier(s); Py_DECREF(s); if (result == 0) tok->done = E_IDENTIFIER; return result; } #endif static int tok_decimal_tail(struct tok_state *tok) { int c; while (1) { do { c = tok_nextc(tok); } while (isdigit(c)); if (c != '_') { break; } c = tok_nextc(tok); if (!isdigit(c)) { tok->done = E_TOKEN; tok_backup(tok, c); return 0; } } return c; } /* Get next token, after space stripping etc. */ static int tok_get(struct tok_state *tok, char **p_start, char **p_end) { int c; int blankline, nonascii; *p_start = *p_end = NULL; nextline: tok->start = NULL; blankline = 0; /* Get indentation level */ if (tok->atbol) { int col = 0; int altcol = 0; tok->atbol = 0; for (;;) { c = tok_nextc(tok); if (c == ' ') { col++, altcol++; } else if (c == '\t') { col = (col/tok->tabsize + 1) * tok->tabsize; altcol = (altcol/tok->alttabsize + 1) * tok->alttabsize; } else if (c == '\014') {/* Control-L (formfeed) */ col = altcol = 0; /* For Emacs users */ } else { break; } } tok_backup(tok, c); if (c == '#' || c == '\n') { /* Lines with only whitespace and/or comments shouldn't affect the indentation and are not passed to the parser as NEWLINE tokens, except *totally* empty lines in interactive mode, which signal the end of a command group. */ if (col == 0 && c == '\n' && tok->prompt != NULL) { blankline = 0; /* Let it through */ } else { blankline = 1; /* Ignore completely */ } /* We can't jump back right here since we still may need to skip to the end of a comment */ } if (!blankline && tok->level == 0) { if (col == tok->indstack[tok->indent]) { /* No change */ if (altcol != tok->altindstack[tok->indent]) { if (indenterror(tok)) { return ERRORTOKEN; } } } else if (col > tok->indstack[tok->indent]) { /* Indent -- always one */ if (tok->indent+1 >= MAXINDENT) { tok->done = E_TOODEEP; tok->cur = tok->inp; return ERRORTOKEN; } if (altcol <= tok->altindstack[tok->indent]) { if (indenterror(tok)) { return ERRORTOKEN; } } tok->pendin++; tok->indstack[++tok->indent] = col; tok->altindstack[tok->indent] = altcol; } else /* col < tok->indstack[tok->indent] */ { /* Dedent -- any number, must be consistent */ while (tok->indent > 0 && col < tok->indstack[tok->indent]) { tok->pendin--; tok->indent--; } if (col != tok->indstack[tok->indent]) { tok->done = E_DEDENT; tok->cur = tok->inp; return ERRORTOKEN; } if (altcol != tok->altindstack[tok->indent]) { if (indenterror(tok)) { return ERRORTOKEN; } } } } } tok->start = tok->cur; /* Return pending indents/dedents */ if (tok->pendin != 0) { if (tok->pendin < 0) { tok->pendin++; return DEDENT; } else { tok->pendin--; return INDENT; } } if (tok->async_def && !blankline && tok->level == 0 /* There was a NEWLINE after ASYNC DEF, so we're past the signature. */ && tok->async_def_nl /* Current indentation level is less than where the async function was defined */ && tok->async_def_indent >= tok->indent) { tok->async_def = 0; tok->async_def_indent = 0; tok->async_def_nl = 0; } again: tok->start = NULL; /* Skip spaces */ do { c = tok_nextc(tok); } while (c == ' ' || c == '\t' || c == '\014'); /* Set start of current token */ if (tok->cur) tok->start = tok->cur - 1; /* Skip comment */ if (c == '#') { while (c != EOF && c != '\n') { c = tok_nextc(tok); } } /* Check for EOF and errors now */ if (c == EOF) { return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN; } /* Identifier (most frequent token!) */ nonascii = 0; if (is_potential_identifier_start(c)) { /* Process the various legal combinations of b"", r"", u"", and f"". */ int saw_b = 0, saw_r = 0, saw_u = 0, saw_f = 0; while (1) { if (!(saw_b || saw_u || saw_f) && (c == 'b' || c == 'B')) saw_b = 1; /* Since this is a backwards compatibility support literal we don't want to support it in arbitrary order like byte literals. */ else if (!(saw_b || saw_u || saw_r || saw_f) && (c == 'u'|| c == 'U')) { saw_u = 1; } /* ur"" and ru"" are not supported */ else if (!(saw_r || saw_u) && (c == 'r' || c == 'R')) { saw_r = 1; } else if (!(saw_f || saw_b || saw_u) && (c == 'f' || c == 'F')) { saw_f = 1; } else { break; } c = tok_nextc(tok); if (c == '"' || c == '\'') { goto letter_quote; } } while (is_potential_identifier_char(c)) { if (c >= 128) { nonascii = 1; } c = tok_nextc(tok); } tok_backup(tok, c); if (nonascii && !verify_identifier(tok)) { return ERRORTOKEN; } *p_start = tok->start; *p_end = tok->cur; /* async/await parsing block. */ if (tok->cur - tok->start == 5) { /* Current token length is 5. */ if (tok->async_def) { /* We're inside an 'async def' function. */ if (!bcmp(tok->start, "async", 5)) { return ASYNC; } if (!bcmp(tok->start, "await", 5)) { return AWAIT; } } else if (!bcmp(tok->start, "async", 5)) { /* The current token is 'async'. Look ahead one token.*/ int async_def_prev = tok->async_def; tok->async_def = 2; struct tok_state ahead_tok; char *ahead_tok_start = NULL, *ahead_tok_end = NULL; int ahead_tok_kind; memcpy(&ahead_tok, tok, sizeof(ahead_tok)); ahead_tok_kind = tok_get(&ahead_tok, &ahead_tok_start, &ahead_tok_end); if (ahead_tok_kind == NAME && ahead_tok.cur - ahead_tok.start == 3 && !bcmp(ahead_tok.start, "def", 3)) { /* The next token is going to be 'def', so instead of returning 'async' NAME token, we return ASYNC. */ tok->async_def_indent = tok->indent; tok->async_def = 1; return ASYNC; } else{ tok->async_def = async_def_prev; } } } return NAME; } /* Newline */ if (c == '\n') { tok->atbol = 1; if (blankline || tok->level > 0) { goto nextline; } *p_start = tok->start; *p_end = tok->cur - 1; /* Leave '\n' out of the string */ tok->cont_line = 0; if (tok->async_def) { /* We're somewhere inside an 'async def' function, and we've encountered a NEWLINE after its signature. */ tok->async_def_nl = 1; } return NEWLINE; } /* Period or number starting with period? */ if (c == '.') { c = tok_nextc(tok); if (isdigit(c)) { goto fraction; } else if (c == '.') { c = tok_nextc(tok); if (c == '.') { *p_start = tok->start; *p_end = tok->cur; return ELLIPSIS; } else { tok_backup(tok, c); } tok_backup(tok, '.'); } else { tok_backup(tok, c); } *p_start = tok->start; *p_end = tok->cur; return DOT; } /* Number */ if (isdigit(c)) { if (c == '0') { /* Hex, octal or binary -- maybe. */ c = tok_nextc(tok); if (c == 'x' || c == 'X') { /* Hex */ c = tok_nextc(tok); do { if (c == '_') { c = tok_nextc(tok); } if (!isxdigit(c)) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } do { c = tok_nextc(tok); } while (isxdigit(c)); } while (c == '_'); } else if (c == 'o' || c == 'O') { /* Octal */ c = tok_nextc(tok); do { if (c == '_') { c = tok_nextc(tok); } if (c < '0' || c >= '8') { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } do { c = tok_nextc(tok); } while ('0' <= c && c < '8'); } while (c == '_'); } else if (c == 'b' || c == 'B') { /* Binary */ c = tok_nextc(tok); do { if (c == '_') { c = tok_nextc(tok); } if (c != '0' && c != '1') { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } do { c = tok_nextc(tok); } while (c == '0' || c == '1'); } while (c == '_'); } else { int nonoctal = 0; /* maybe old-style octal; c is first char of it */ /* in any case, allow '0' as a literal */ while (1) { if (c == '_') { c = tok_nextc(tok); if (!isdigit(c)) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } } if (c != '0') { break; } c = tok_nextc(tok); } /* [jart] restore octal */ if ('1' <= c && c <= '7') { while (1) { if (c == '_') { c = tok_nextc(tok); if (!('0' <= c && c <= '7')) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } } if (!('0' <= c && c <= '7')) { break; } c = tok_nextc(tok); } } if (isdigit(c)) { nonoctal = 1; c = tok_decimal_tail(tok); if (c == 0) { return ERRORTOKEN; } } if (c == '.') { c = tok_nextc(tok); goto fraction; } else if (c == 'e' || c == 'E') { goto exponent; } else if (c == 'j' || c == 'J') { goto imaginary; } else if (nonoctal) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } } } else { /* Decimal */ c = tok_decimal_tail(tok); if (c == 0) { return ERRORTOKEN; } { /* Accept floating point numbers. */ if (c == '.') { c = tok_nextc(tok); fraction: /* Fraction */ if (isdigit(c)) { c = tok_decimal_tail(tok); if (c == 0) { return ERRORTOKEN; } } } if (c == 'e' || c == 'E') { int e; exponent: e = c; /* Exponent part */ c = tok_nextc(tok); if (c == '+' || c == '-') { c = tok_nextc(tok); if (!isdigit(c)) { tok->done = E_TOKEN; tok_backup(tok, c); return ERRORTOKEN; } } else if (!isdigit(c)) { tok_backup(tok, c); tok_backup(tok, e); *p_start = tok->start; *p_end = tok->cur; return NUMBER; } c = tok_decimal_tail(tok); if (c == 0) { return ERRORTOKEN; } } if (c == 'j' || c == 'J') { /* Imaginary part */ imaginary: c = tok_nextc(tok); } } } tok_backup(tok, c); *p_start = tok->start; *p_end = tok->cur; return NUMBER; } letter_quote: /* String */ if (c == '\'' || c == '"') { int quote = c; int quote_size = 1; /* 1 or 3 */ int end_quote_size = 0; /* Find the quote size and start of string */ c = tok_nextc(tok); if (c == quote) { c = tok_nextc(tok); if (c == quote) { quote_size = 3; } else { end_quote_size = 1; /* empty string found */ } } if (c != quote) { tok_backup(tok, c); } /* Get rest of string */ while (end_quote_size != quote_size) { c = tok_nextc(tok); if (c == EOF) { if (quote_size == 3) { tok->done = E_EOFS; } else { tok->done = E_EOLS; } tok->cur = tok->inp; return ERRORTOKEN; } if (quote_size == 1 && c == '\n') { tok->done = E_EOLS; tok->cur = tok->inp; return ERRORTOKEN; } if (c == quote) { end_quote_size += 1; } else { end_quote_size = 0; if (c == '\\') { tok_nextc(tok); /* skip escaped char */ } } } *p_start = tok->start; *p_end = tok->cur; return STRING; } /* Line continuation */ if (c == '\\') { c = tok_nextc(tok); if (tok->async_def == 2) { tok->done = E_SYNTAX; return ERRORTOKEN; } if (c != '\n') { tok->done = E_LINECONT; tok->cur = tok->inp; return ERRORTOKEN; } tok->cont_line = 1; goto again; /* Read next line */ } /* Check for two-character token */ { int c2 = tok_nextc(tok); int token = PyToken_TwoChars(c, c2); if (token != OP) { int c3 = tok_nextc(tok); int token3 = PyToken_ThreeChars(c, c2, c3); if (token3 != OP) { token = token3; } else { tok_backup(tok, c3); } *p_start = tok->start; *p_end = tok->cur; return token; } tok_backup(tok, c2); } /* Keep track of parentheses nesting level */ switch (c) { case '(': case '[': case '{': tok->level++; break; case ')': case ']': case '}': tok->level--; break; } /* Punctuation character */ *p_start = tok->start; *p_end = tok->cur; return PyToken_OneChar(c); } int PyTokenizer_Get(struct tok_state *tok, char **p_start, char **p_end) { int result = tok_get(tok, p_start, p_end); if (tok->decoding_erred) { result = ERRORTOKEN; tok->done = E_DECODE; } return result; } /* Get the encoding of a Python file. Check for the coding cookie and check if the file starts with a BOM. PyTokenizer_FindEncodingFilename() returns NULL when it can't find the encoding in the first or second line of the file (in which case the encoding should be assumed to be UTF-8). The char* returned is malloc'ed via PyMem_MALLOC() and thus must be freed by the caller. */ char * PyTokenizer_FindEncodingFilename(int fd, PyObject *filename) { struct tok_state *tok; FILE *fp; char *p_start =NULL , *p_end =NULL , *encoding = NULL; #ifndef PGEN fd = _Py_dup(fd); #else fd = dup(fd); #endif if (fd < 0) { return NULL; } fp = fdopen(fd, "r"); if (fp == NULL) { return NULL; } tok = PyTokenizer_FromFile(fp, NULL, NULL, NULL); if (tok == NULL) { fclose(fp); return NULL; } #ifndef PGEN if (filename != NULL) { Py_INCREF(filename); tok->filename = filename; } else { tok->filename = PyUnicode_FromString("<string>"); if (tok->filename == NULL) { fclose(fp); PyTokenizer_Free(tok); return encoding; } } #endif while (tok->lineno < 2 && tok->done == E_OK) { PyTokenizer_Get(tok, &p_start, &p_end); } fclose(fp); if (tok->encoding) { encoding = (char *)PyMem_MALLOC(strlen(tok->encoding) + 1); if (encoding) strcpy(encoding, tok->encoding); } PyTokenizer_Free(tok); return encoding; } char * PyTokenizer_FindEncoding(int fd) { return PyTokenizer_FindEncodingFilename(fd, NULL); } #ifdef Py_DEBUG void tok_dump(int type, char *start, char *end) { printf("%s", _PyParser_TokenNames[type]); if (type == NAME || type == NUMBER || type == STRING || type == OP) printf("(%.*s)", (int)(end - start), start); } #endif
58,199
2,023
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/pgen.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/metagrammar.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pgen.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Include/token.h" /* clang-format off */ /* Description ----------- Input is a grammar in extended BNF (using * for repetition, + for at-least-once repetition, [] for optional parts, | for alternatives and () for grouping). This has already been parsed and turned into a parse tree. Each rule is considered as a regular expression in its own right. It is turned into a Non-deterministic Finite Automaton (NFA), which is then turned into a Deterministic Finite Automaton (DFA), which is then optimized to reduce the number of states. See [Aho&Ullman 77] chapter 3, or similar compiler books (this technique is more often used for lexical analyzers). The DFA's are used by the parser as parsing tables in a special way that's probably unique. Before they are usable, the FIRST sets of all non-terminals are computed. Reference --------- [Aho&Ullman 77] Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977 (first edition) */ extern int Py_DebugFlag; extern int Py_IgnoreEnvironmentFlag; /* needed by Py_GETENV */ /* PART ONE -- CONSTRUCT NFA -- Cf. Algorithm 3.2 from [Aho&Ullman 77] */ typedef struct _nfaarc { int ar_label; int ar_arrow; } nfaarc; typedef struct _nfastate { int st_narcs; nfaarc *st_arc; } nfastate; typedef struct _nfa { int nf_type; char *nf_name; int nf_nstates; nfastate *nf_state; int nf_start, nf_finish; } nfa; /* Forward */ static void compile_rhs(labellist *ll, nfa *nf, node *n, int *pa, int *pb); static void compile_alt(labellist *ll, nfa *nf, node *n, int *pa, int *pb); static void compile_item(labellist *ll, nfa *nf, node *n, int *pa, int *pb); static void compile_atom(labellist *ll, nfa *nf, node *n, int *pa, int *pb); static int addnfastate(nfa *nf) { nfastate *st; nf->nf_state = (nfastate *)PyObject_REALLOC(nf->nf_state, sizeof(nfastate) * (nf->nf_nstates + 1)); if (nf->nf_state == NULL) Py_FatalError("out of mem"); st = &nf->nf_state[nf->nf_nstates++]; st->st_narcs = 0; st->st_arc = NULL; return st - nf->nf_state; } static void addnfaarc(nfa *nf, int from, int to, int lbl) { nfastate *st; nfaarc *ar; st = &nf->nf_state[from]; st->st_arc = (nfaarc *)PyObject_REALLOC(st->st_arc, sizeof(nfaarc) * (st->st_narcs + 1)); if (st->st_arc == NULL) Py_FatalError("out of mem"); ar = &st->st_arc[st->st_narcs++]; ar->ar_label = lbl; ar->ar_arrow = to; } static nfa * newnfa(char *name) { nfa *nf; static int type = NT_OFFSET; /* All types will be disjunct */ nf = (nfa *)PyObject_MALLOC(sizeof(nfa)); if (nf == NULL) Py_FatalError("no mem for new nfa"); nf->nf_type = type++; nf->nf_name = name; /* XXX strdup(name) ??? */ nf->nf_nstates = 0; nf->nf_state = NULL; nf->nf_start = nf->nf_finish = -1; return nf; } typedef struct _nfagrammar { int gr_nnfas; nfa **gr_nfa; labellist gr_ll; } nfagrammar; /* Forward */ static void compile_rule(nfagrammar *gr, node *n); static nfagrammar * newnfagrammar(void) { nfagrammar *gr; gr = (nfagrammar *)PyObject_MALLOC(sizeof(nfagrammar)); if (gr == NULL) Py_FatalError("no mem for new nfa grammar"); gr->gr_nnfas = 0; gr->gr_nfa = NULL; gr->gr_ll.ll_nlabels = 0; gr->gr_ll.ll_label = NULL; addlabel(&gr->gr_ll, ENDMARKER, "EMPTY"); return gr; } static void freenfagrammar(nfagrammar *gr) { for (int i = 0; i < gr->gr_nnfas; i++) { PyObject_FREE(gr->gr_nfa[i]->nf_state); } PyObject_FREE(gr->gr_nfa); PyObject_FREE(gr); } static nfa * addnfa(nfagrammar *gr, char *name) { nfa *nf; nf = newnfa(name); gr->gr_nfa = (nfa **)PyObject_REALLOC(gr->gr_nfa, sizeof(nfa*) * (gr->gr_nnfas + 1)); if (gr->gr_nfa == NULL) Py_FatalError("out of mem"); gr->gr_nfa[gr->gr_nnfas++] = nf; addlabel(&gr->gr_ll, NAME, nf->nf_name); return nf; } #ifdef Py_DEBUG static const char REQNFMT[] = "metacompile: less than %d children\n"; #define REQN(i, count) do { \ if (i < count) { \ fprintf(stderr, REQNFMT, count); \ Py_FatalError("REQN"); \ } \ } while (0) #else #define REQN(i, count) /* empty */ #endif static nfagrammar * metacompile(node *n) { nfagrammar *gr; int i; if (Py_DebugFlag) printf("Compiling (meta-) parse tree into NFA grammar\n"); gr = newnfagrammar(); REQ(n, MSTART); i = n->n_nchildren - 1; /* Last child is ENDMARKER */ n = n->n_child; for (; --i >= 0; n++) { if (n->n_type != NEWLINE) compile_rule(gr, n); } return gr; } static void compile_rule(nfagrammar *gr, node *n) { nfa *nf; REQ(n, RULE); REQN(n->n_nchildren, 4); n = n->n_child; REQ(n, NAME); nf = addnfa(gr, n->n_str); n++; REQ(n, COLON); n++; REQ(n, RHS); compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish); n++; REQ(n, NEWLINE); } static void compile_rhs(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { int i; int a, b; REQ(n, RHS); i = n->n_nchildren; REQN(i, 1); n = n->n_child; REQ(n, ALT); compile_alt(ll, nf, n, pa, pb); if (--i <= 0) return; n++; a = *pa; b = *pb; *pa = addnfastate(nf); *pb = addnfastate(nf); addnfaarc(nf, *pa, a, EMPTY); addnfaarc(nf, b, *pb, EMPTY); for (; --i >= 0; n++) { REQ(n, VBAR); REQN(i, 1); --i; n++; REQ(n, ALT); compile_alt(ll, nf, n, &a, &b); addnfaarc(nf, *pa, a, EMPTY); addnfaarc(nf, b, *pb, EMPTY); } } static void compile_alt(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { int i; int a, b; REQ(n, ALT); i = n->n_nchildren; REQN(i, 1); n = n->n_child; REQ(n, ITEM); compile_item(ll, nf, n, pa, pb); --i; n++; for (; --i >= 0; n++) { REQ(n, ITEM); compile_item(ll, nf, n, &a, &b); addnfaarc(nf, *pb, a, EMPTY); *pb = b; } } static void compile_item(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { int i; int a, b; REQ(n, ITEM); i = n->n_nchildren; REQN(i, 1); n = n->n_child; if (n->n_type == LSQB) { REQN(i, 3); n++; REQ(n, RHS); *pa = addnfastate(nf); *pb = addnfastate(nf); addnfaarc(nf, *pa, *pb, EMPTY); compile_rhs(ll, nf, n, &a, &b); addnfaarc(nf, *pa, a, EMPTY); addnfaarc(nf, b, *pb, EMPTY); REQN(i, 1); n++; REQ(n, RSQB); } else { compile_atom(ll, nf, n, pa, pb); if (--i <= 0) return; n++; addnfaarc(nf, *pb, *pa, EMPTY); if (n->n_type == STAR) *pb = *pa; else REQ(n, PLUS); } } static void compile_atom(labellist *ll, nfa *nf, node *n, int *pa, int *pb) { int i; REQ(n, ATOM); i = n->n_nchildren; (void)i; /* Don't warn about set but unused */ REQN(i, 1); n = n->n_child; if (n->n_type == LPAR) { REQN(i, 3); n++; REQ(n, RHS); compile_rhs(ll, nf, n, pa, pb); n++; REQ(n, RPAR); } else if (n->n_type == NAME || n->n_type == STRING) { *pa = addnfastate(nf); *pb = addnfastate(nf); addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str)); } else REQ(n, NAME); } static void dumpstate(labellist *ll, nfa *nf, int istate) { nfastate *st; int i; nfaarc *ar; printf("%c%2d%c", istate == nf->nf_start ? '*' : ' ', istate, istate == nf->nf_finish ? '.' : ' '); st = &nf->nf_state[istate]; ar = st->st_arc; for (i = 0; i < st->st_narcs; i++) { if (i > 0) printf("\n "); printf("-> %2d %s", ar->ar_arrow, PyGrammar_LabelRepr(&ll->ll_label[ar->ar_label])); ar++; } printf("\n"); } static void dumpnfa(labellist *ll, nfa *nf) { int i; printf("NFA '%s' has %d states; start %d, finish %d\n", nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish); for (i = 0; i < nf->nf_nstates; i++) dumpstate(ll, nf, i); } /* PART TWO -- CONSTRUCT DFA -- Algorithm 3.1 from [Aho&Ullman 77] */ static void addclosure(bitset ss, nfa *nf, int istate) { if (addbit(ss, istate)) { nfastate *st = &nf->nf_state[istate]; nfaarc *ar = st->st_arc; int i; for (i = st->st_narcs; --i >= 0; ) { if (ar->ar_label == EMPTY) addclosure(ss, nf, ar->ar_arrow); ar++; } } } typedef struct _ss_arc { bitset sa_bitset; int sa_arrow; int sa_label; } ss_arc; typedef struct _ss_state { bitset ss_ss; int ss_narcs; struct _ss_arc *ss_arc; int ss_deleted; int ss_finish; int ss_rename; } ss_state; typedef struct _ss_dfa { int sd_nstates; ss_state *sd_state; } ss_dfa; /* Forward */ static void printssdfa(int xx_nstates, ss_state *xx_state, int nbits, labellist *ll, const char *msg); static void simplify(int xx_nstates, ss_state *xx_state); static void convert(dfa *d, int xx_nstates, ss_state *xx_state); static void makedfa(nfagrammar *gr, nfa *nf, dfa *d) { int nbits = nf->nf_nstates; bitset ss; int xx_nstates; ss_state *xx_state, *yy; ss_arc *zz; int istate, jstate, iarc, jarc, ibit; nfastate *st; nfaarc *ar; ss = newbitset(nbits); addclosure(ss, nf, nf->nf_start); xx_state = (ss_state *)PyObject_MALLOC(sizeof(ss_state)); if (xx_state == NULL) Py_FatalError("no mem for xx_state in makedfa"); xx_nstates = 1; yy = &xx_state[0]; yy->ss_ss = ss; yy->ss_narcs = 0; yy->ss_arc = NULL; yy->ss_deleted = 0; yy->ss_finish = testbit(ss, nf->nf_finish); if (yy->ss_finish) printf("Error: nonterminal '%s' may produce empty.\n", nf->nf_name); /* This algorithm is from a book written before the invention of structured programming... */ /* For each unmarked state... */ for (istate = 0; istate < xx_nstates; ++istate) { size_t size; yy = &xx_state[istate]; ss = yy->ss_ss; /* For all its states... */ for (ibit = 0; ibit < nf->nf_nstates; ++ibit) { if (!testbit(ss, ibit)) continue; st = &nf->nf_state[ibit]; /* For all non-empty arcs from this state... */ for (iarc = 0; iarc < st->st_narcs; iarc++) { ar = &st->st_arc[iarc]; if (ar->ar_label == EMPTY) continue; /* Look up in list of arcs from this state */ for (jarc = 0; jarc < yy->ss_narcs; ++jarc) { zz = &yy->ss_arc[jarc]; if (ar->ar_label == zz->sa_label) goto found; } /* Add new arc for this state */ size = sizeof(ss_arc) * (yy->ss_narcs + 1); yy->ss_arc = (ss_arc *)PyObject_REALLOC( yy->ss_arc, size); if (yy->ss_arc == NULL) Py_FatalError("out of mem"); zz = &yy->ss_arc[yy->ss_narcs++]; zz->sa_label = ar->ar_label; zz->sa_bitset = newbitset(nbits); zz->sa_arrow = -1; found: ; /* Add destination */ addclosure(zz->sa_bitset, nf, ar->ar_arrow); } } /* Now look up all the arrow states */ for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) { zz = &xx_state[istate].ss_arc[jarc]; for (jstate = 0; jstate < xx_nstates; jstate++) { if (samebitset(zz->sa_bitset, xx_state[jstate].ss_ss, nbits)) { zz->sa_arrow = jstate; goto done; } } size = sizeof(ss_state) * (xx_nstates + 1); xx_state = (ss_state *)PyObject_REALLOC(xx_state, size); if (xx_state == NULL) Py_FatalError("out of mem"); zz->sa_arrow = xx_nstates; yy = &xx_state[xx_nstates++]; yy->ss_ss = zz->sa_bitset; yy->ss_narcs = 0; yy->ss_arc = NULL; yy->ss_deleted = 0; yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish); done: ; } } if (Py_DebugFlag) printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, "before minimizing"); simplify(xx_nstates, xx_state); if (Py_DebugFlag) printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll, "after minimizing"); convert(d, xx_nstates, xx_state); for (int i = 0; i < xx_nstates; i++) { for (int j = 0; j < xx_state[i].ss_narcs; j++) delbitset(xx_state[i].ss_arc[j].sa_bitset); PyObject_FREE(xx_state[i].ss_arc); } PyObject_FREE(xx_state); } static void printssdfa(int xx_nstates, ss_state *xx_state, int nbits, labellist *ll, const char *msg) { int i, ibit, iarc; ss_state *yy; ss_arc *zz; printf("Subset DFA %s\n", msg); for (i = 0; i < xx_nstates; i++) { yy = &xx_state[i]; if (yy->ss_deleted) continue; printf(" Subset %d", i); if (yy->ss_finish) printf(" (finish)"); printf(" { "); for (ibit = 0; ibit < nbits; ibit++) { if (testbit(yy->ss_ss, ibit)) printf("%d ", ibit); } printf("}\n"); for (iarc = 0; iarc < yy->ss_narcs; iarc++) { zz = &yy->ss_arc[iarc]; printf(" Arc to state %d, label %s\n", zz->sa_arrow, PyGrammar_LabelRepr( &ll->ll_label[zz->sa_label])); } } } /* PART THREE -- SIMPLIFY DFA */ /* Simplify the DFA by repeatedly eliminating states that are equivalent to another oner. This is NOT Algorithm 3.3 from [Aho&Ullman 77]. It does not always finds the minimal DFA, but it does usually make a much smaller one... (For an example of sub-optimal behavior, try S: x a b+ | y a b+.) */ static int samestate(ss_state *s1, ss_state *s2) { int i; if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish) return 0; for (i = 0; i < s1->ss_narcs; i++) { if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow || s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label) return 0; } return 1; } static void renamestates(int xx_nstates, ss_state *xx_state, int from, int to) { int i, j; if (Py_DebugFlag) printf("Rename state %d to %d.\n", from, to); for (i = 0; i < xx_nstates; i++) { if (xx_state[i].ss_deleted) continue; for (j = 0; j < xx_state[i].ss_narcs; j++) { if (xx_state[i].ss_arc[j].sa_arrow == from) xx_state[i].ss_arc[j].sa_arrow = to; } } } static void simplify(int xx_nstates, ss_state *xx_state) { int changes; int i, j; do { changes = 0; for (i = 1; i < xx_nstates; i++) { if (xx_state[i].ss_deleted) continue; for (j = 0; j < i; j++) { if (xx_state[j].ss_deleted) continue; if (samestate(&xx_state[i], &xx_state[j])) { xx_state[i].ss_deleted++; renamestates(xx_nstates, xx_state, i, j); changes++; break; } } } } while (changes); } /* PART FOUR -- GENERATE PARSING TABLES */ /* Convert the DFA into a grammar that can be used by our parser */ static void convert(dfa *d, int xx_nstates, ss_state *xx_state) { int i, j; ss_state *yy; ss_arc *zz; for (i = 0; i < xx_nstates; i++) { yy = &xx_state[i]; if (yy->ss_deleted) continue; yy->ss_rename = addstate(d); } for (i = 0; i < xx_nstates; i++) { yy = &xx_state[i]; if (yy->ss_deleted) continue; for (j = 0; j < yy->ss_narcs; j++) { zz = &yy->ss_arc[j]; addarc(d, yy->ss_rename, xx_state[zz->sa_arrow].ss_rename, zz->sa_label); } if (yy->ss_finish) addarc(d, yy->ss_rename, yy->ss_rename, 0); } d->d_initial = 0; } /* PART FIVE -- GLUE IT ALL TOGETHER */ static grammar * maketables(nfagrammar *gr) { int i; nfa *nf; dfa *d; grammar *g; if (gr->gr_nnfas == 0) return NULL; g = newgrammar(gr->gr_nfa[0]->nf_type); /* XXX first rule must be start rule */ g->g_ll = gr->gr_ll; for (i = 0; i < gr->gr_nnfas; i++) { nf = gr->gr_nfa[i]; if (Py_DebugFlag) { printf("Dump of NFA for '%s' ...\n", nf->nf_name); dumpnfa(&gr->gr_ll, nf); printf("Making DFA for '%s' ...\n", nf->nf_name); } d = adddfa(g, nf->nf_type, nf->nf_name); makedfa(gr, gr->gr_nfa[i], d); } return g; } grammar * pgen(node *n) { nfagrammar *gr; grammar *g; gr = metacompile(n); g = maketables(gr); translatelabels(g); addfirstsets(g); freenfagrammar(gr); return g; } grammar * Py_pgen(node *n) { return pgen(n); }
19,260
727
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/node.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/intrin/bsr.h" #include "third_party/python/Include/errcode.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/objimpl.h" /* clang-format off */ node * PyNode_New(int type) { node *n = (node *) PyObject_MALLOC(1 * sizeof(node)); if (n == NULL) return NULL; n->n_type = type; n->n_str = NULL; n->n_lineno = 0; n->n_nchildren = 0; n->n_child = NULL; return n; } /* See comments at XXXROUNDUP below. Returns -1 on overflow. */ static int fancy_roundup(int x) { /* Round up to the closest power of 2 >= n. */ int r; assert(x > 128); r = 1u << (_bsr(x - 1) + 1); /* hacker's delight */ return r > 0 ? r : -1; } /* A gimmick to make massive numbers of reallocs quicker. The result is * a number >= the input. In PyNode_AddChild, it's used like so, when * we're about to add child number current_size + 1: * * if XXXROUNDUP(current_size) < XXXROUNDUP(current_size + 1): * allocate space for XXXROUNDUP(current_size + 1) total children * else: * we already have enough space * * Since a node starts out empty, we must have * * XXXROUNDUP(0) < XXXROUNDUP(1) * * so that we allocate space for the first child. One-child nodes are very * common (presumably that would change if we used a more abstract form * of syntax tree), so to avoid wasting memory it's desirable that * XXXROUNDUP(1) == 1. That in turn forces XXXROUNDUP(0) == 0. * * Else for 2 <= n <= 128, we round up to the closest multiple of 4. Why 4? * Rounding up to a multiple of an exact power of 2 is very efficient, and * most nodes with more than one child have <= 4 kids. * * Else we call fancy_roundup() to grow proportionately to n. We've got an * extreme case then (like test_longexp.py), and on many platforms doing * anything less than proportional growth leads to exorbitant runtime * (e.g., MacPython), or extreme fragmentation of user address space (e.g., * Win98). * * In a run of compileall across the 2.3a0 Lib directory, Andrew MacIntyre * reported that, with this scheme, 89% of PyObject_REALLOC calls in * PyNode_AddChild passed 1 for the size, and 9% passed 4. So this usually * wastes very little memory, but is very effective at sidestepping * platform-realloc disasters on vulnerable platforms. * * Note that this would be straightforward if a node stored its current * capacity. The code is tricky to avoid that. */ #define XXXROUNDUP(n) ((n) <= 1 ? (n) : \ (n) <= 128 ? (int)_Py_SIZE_ROUND_UP((n), 4) : \ fancy_roundup(n)) int PyNode_AddChild(node *n1, int type, char *str, int lineno, int col_offset) { const int nch = n1->n_nchildren; int current_capacity; int required_capacity; node *n; if (nch == INT_MAX || nch < 0) return E_OVERFLOW; current_capacity = XXXROUNDUP(nch); required_capacity = XXXROUNDUP(nch + 1); if (current_capacity < 0 || required_capacity < 0) return E_OVERFLOW; if (current_capacity < required_capacity) { if ((size_t)required_capacity > SIZE_MAX / sizeof(node)) { return E_NOMEM; } n = n1->n_child; n = (node *) PyObject_REALLOC(n, required_capacity * sizeof(node)); if (n == NULL) return E_NOMEM; n1->n_child = n; } n = &n1->n_child[n1->n_nchildren++]; n->n_type = type; n->n_str = str; n->n_lineno = lineno; n->n_col_offset = col_offset; n->n_nchildren = 0; n->n_child = NULL; return 0; } /* Forward */ static void freechildren(node *); static Py_ssize_t sizeofchildren(node *n); void PyNode_Free(node *n) { if (n != NULL) { freechildren(n); PyObject_FREE(n); } } Py_ssize_t _PyNode_SizeOf(node *n) { Py_ssize_t res = 0; if (n != NULL) res = sizeof(node) + sizeofchildren(n); return res; } static void freechildren(node *n) { int i; for (i = NCH(n); --i >= 0; ) freechildren(CHILD(n, i)); if (n->n_child != NULL) PyObject_FREE(n->n_child); if (STR(n) != NULL) PyObject_FREE(STR(n)); } static Py_ssize_t sizeofchildren(node *n) { Py_ssize_t res = 0; int i; for (i = NCH(n); --i >= 0; ) res += sizeofchildren(CHILD(n, i)); if (n->n_child != NULL) /* allocated size of n->n_child array */ res += XXXROUNDUP(NCH(n)) * sizeof(node); if (STR(n) != NULL) res += strlen(STR(n)) + 1; return res; }
5,427
168
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/tokenizer.h
#ifndef Py_TOKENIZER_H #define Py_TOKENIZER_H #include "third_party/python/Include/object.h" #include "third_party/python/Include/token.h" #ifdef __cplusplus extern "C" { #endif /* clang-format off */ #define MAXINDENT 100 /* Max indentation level */ enum decoding_state { STATE_INIT, STATE_RAW, STATE_NORMAL /* have a codec associated with input */ }; /* Tokenizer state */ struct tok_state { /* Input state; buf <= cur <= inp <= end */ /* NB an entire line is held in the buffer */ char *buf; /* Input buffer, or NULL; malloc'ed if fp != NULL */ char *cur; /* Next character in buffer */ char *inp; /* End of data in buffer */ char *end; /* End of input buffer if buf != NULL */ char *start; /* Start of current token if not NULL */ int done; /* E_OK normally, E_EOF at EOF, otherwise error code */ /* NB If done != E_OK, cur must be == inp!!! */ FILE *fp; /* Rest of input; NULL if tokenizing a string */ int tabsize; /* Tab spacing */ int indent; /* Current indentation index */ int indstack[MAXINDENT]; /* Stack of indents */ int atbol; /* Nonzero if at begin of new line */ int pendin; /* Pending indents (if > 0) or dedents (if < 0) */ const char *prompt, *nextprompt; /* For interactive prompting */ int lineno; /* Current line number */ int level; /* () [] {} Parentheses nesting level */ /* Used to allow free continuations inside them */ /* Stuff for checking on different tab sizes */ #ifndef PGEN /* pgen doesn't have access to Python codecs, it cannot decode the input filename. The bytes filename might be kept, but it is only used by indenterror() and it is not really needed: pgen only compiles one file (Grammar/Grammar). */ PyObject *filename; #endif int altwarning; /* Issue warning if alternate tabs don't match */ int alterror; /* Issue error if alternate tabs don't match */ int alttabsize; /* Alternate tab spacing */ int altindstack[MAXINDENT]; /* Stack of alternate indents */ /* Stuff for PEP 0263 */ enum decoding_state decoding_state; int decoding_erred; /* whether erred in decoding */ int read_coding_spec; /* whether 'coding:...' has been read */ char *encoding; /* Source encoding. */ int cont_line; /* whether we are in a continuation line. */ const char* line_start; /* pointer to start of current line */ #ifndef PGEN PyObject *decoding_readline; /* open(...).readline */ PyObject *decoding_buffer; #endif const char* enc; /* Encoding for the current str. */ const char* str; const char* input; /* Tokenizer's newline translated copy of the string. */ /* async/await related fields; can be removed in 3.7 when async and await become normal keywords. */ int async_def; /* =1 if tokens are inside an 'async def' body. */ int async_def_indent; /* Indentation level of the outermost 'async def'. */ int async_def_nl; /* =1 if the outermost 'async def' had at least one NEWLINE token after it. */ }; extern struct tok_state *PyTokenizer_FromString(const char *, int); extern struct tok_state *PyTokenizer_FromUTF8(const char *, int); extern struct tok_state *PyTokenizer_FromFile(FILE *, const char*, const char *, const char *); extern void PyTokenizer_Free(struct tok_state *); extern int PyTokenizer_Get(struct tok_state *, char **, char **); extern char * PyTokenizer_RestoreEncoding(struct tok_state* tok, int len, int *offset); #ifdef __cplusplus } #endif #endif /* !Py_TOKENIZER_H */
3,879
87
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/bitset.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/bitset.h" #include "third_party/python/Include/objimpl.h" /* clang-format off */ bitset newbitset(int nbits) { int nbytes = NBYTES(nbits); bitset ss = (char *)PyObject_MALLOC(sizeof(BYTE) * nbytes); if (ss == NULL) Py_FatalError("no mem for bitset"); ss += nbytes; while (--nbytes >= 0) *--ss = 0; return ss; } void delbitset(bitset ss) { PyObject_FREE(ss); } int addbit(bitset ss, int ibit) { int ibyte = BIT2BYTE(ibit); BYTE mask = BIT2MASK(ibit); if (ss[ibyte] & mask) return 0; /* Bit already set */ ss[ibyte] |= mask; return 1; } #if 0 /* Now a macro */ int testbit(bitset ss, int ibit) { return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0; } #endif int samebitset(bitset ss1, bitset ss2, int nbits) { int i; for (i = NBYTES(nbits); --i >= 0; ) if (*ss1++ != *ss2++) return 0; return 1; } void mergebitset(bitset ss1, bitset ss2, int nbits) { int i; for (i = NBYTES(nbits); --i >= 0; ) *ss1++ |= *ss2++; }
1,899
71
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/parser.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "third_party/python/Include/errcode.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/token.h" #include "third_party/python/Parser/parser.h" /* clang-format off */ /* Description ----------- The parser's interface is different than usual: the function addtoken() must be called for each token in the input. This makes it possible to turn it into an incremental parsing system later. The parsing system constructs a parse tree as it goes. A parsing rule is represented as a Deterministic Finite-state Automaton (DFA). A node in a DFA represents a state of the parser; an arc represents a transition. Transitions are either labeled with terminal symbols or with non-terminals. When the parser decides to follow an arc labeled with a non-terminal, it is invoked recursively with the DFA representing the parsing rule for that as its initial state; when that DFA accepts, the parser that invoked it continues. The parse tree constructed by the recursively called parser is inserted as a child in the current parse tree. The DFA's can be constructed automatically from a more conventional language description. An extended LL(1) grammar (ELL(1)) is suitable. Certain restrictions make the parser's life easier: rules that can produce the empty string should be outlawed (there are other ways to put loops or optional parts in the language). To avoid the need to construct FIRST sets, we can require that all but the last alternative of a rule (really: arc going out of a DFA's state) must begin with a terminal symbol. As an example, consider this grammar: expr: term (OP term)* term: CONSTANT | '(' expr ')' The DFA corresponding to the rule for expr is: ------->.---term-->.-------> ^ | | | \----OP----/ The parse tree generated for the input a+b is: (expr: (term: (NAME: a)), (OP: +), (term: (NAME: b))) TODO(XXX): error recovery */ #ifdef Py_DEBUG extern int Py_DebugFlag; #define D(x) if (!Py_DebugFlag); else x #else #define D(x) #endif /* STACK DATA TYPE */ static void s_reset(stack *); static void s_reset(stack *s) { s->s_top = &s->s_base[MAXSTACK]; } #define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK]) static int s_push(stack *s, dfa *d, node *parent) { stackentry *top; if (s->s_top == s->s_base) { fprintf(stderr, "s_push: parser stack overflow\n"); return E_NOMEM; } top = --s->s_top; top->s_dfa = d; top->s_parent = parent; top->s_state = 0; return 0; } #ifdef Py_DEBUG static void s_pop(stack *s) { if (s_empty(s)) Py_FatalError("s_pop: parser stack underflow -- FATAL"); s->s_top++; } #else /* !Py_DEBUG */ #define s_pop(s) (s)->s_top++ #endif /* PARSER CREATION */ parser_state * PyParser_New(grammar *g, int start) { parser_state *ps; if (!g->g_accel) PyGrammar_AddAccelerators(g); ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state)); if (ps == NULL) return NULL; ps->p_grammar = g; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD ps->p_flags = 0; #endif ps->p_tree = PyNode_New(start); if (ps->p_tree == NULL) { PyMem_FREE(ps); return NULL; } s_reset(&ps->p_stack); (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree); return ps; } void PyParser_Delete(parser_state *ps) { /* NB If you want to save the parse tree, you must set p_tree to NULL before calling delparser! */ PyNode_Free(ps->p_tree); PyMem_FREE(ps); } /* PARSER STACK OPERATIONS */ static int shift(stack *s, int type, char *str, int newstate, int lineno, int col_offset) { int err; assert(!s_empty(s)); err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset); if (err) return err; s->s_top->s_state = newstate; return 0; } static int push(stack *s, int type, dfa *d, int newstate, int lineno, int col_offset) { int err; node *n; n = s->s_top->s_parent; assert(!s_empty(s)); err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset); if (err) return err; s->s_top->s_state = newstate; return s_push(s, d, CHILD(n, NCH(n)-1)); } /* PARSER PROPER */ static int classify(parser_state *ps, int type, const char *str) { grammar *g = ps->p_grammar; int n = g->g_ll.ll_nlabels; if (type == NAME) { label *l = g->g_ll.ll_label; int i; for (i = n; i > 0; i--, l++) { if (l->lb_type != NAME || l->lb_str == NULL || l->lb_str[0] != str[0] || strcmp(l->lb_str, str) != 0) continue; #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 /* Leaving this in as an example */ if (!(ps->p_flags & CO_FUTURE_WITH_STATEMENT)) { if (str[0] == 'w' && strcmp(str, "with") == 0) break; /* not a keyword yet */ else if (str[0] == 'a' && strcmp(str, "as") == 0) break; /* not a keyword yet */ } #endif #endif D(printf("It's a keyword\n")); return n - i; } } { label *l = g->g_ll.ll_label; int i; for (i = n; i > 0; i--, l++) { if (l->lb_type == type && l->lb_str == NULL) { D(printf("It's a token we know\n")); return n - i; } } } D(printf("Illegal token\n")); return -1; } #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 /* Leaving this in as an example */ static void future_hack(parser_state *ps) { node *n = ps->p_stack.s_top->s_parent; node *ch, *cch; int i; /* from __future__ import ..., must have at least 4 children */ n = CHILD(n, 0); if (NCH(n) < 4) return; ch = CHILD(n, 0); if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0) return; ch = CHILD(n, 1); if (NCH(ch) == 1 && STR(CHILD(ch, 0)) && strcmp(STR(CHILD(ch, 0)), "__future__") != 0) return; ch = CHILD(n, 3); /* ch can be a star, a parenthesis or import_as_names */ if (TYPE(ch) == STAR) return; if (TYPE(ch) == LPAR) ch = CHILD(n, 4); for (i = 0; i < NCH(ch); i += 2) { cch = CHILD(ch, i); if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) { char *str_ch = STR(CHILD(cch, 0)); if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) { ps->p_flags |= CO_FUTURE_WITH_STATEMENT; } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) { ps->p_flags |= CO_FUTURE_PRINT_FUNCTION; } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) { ps->p_flags |= CO_FUTURE_UNICODE_LITERALS; } } } } #endif #endif /* future keyword */ int PyParser_AddToken(parser_state *ps, int type, char *str, int lineno, int col_offset, int *expected_ret) { int ilabel; int err; D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str)); /* Find out which label this token is */ ilabel = classify(ps, type, str); if (ilabel < 0) return E_SYNTAX; /* Loop until the token is shifted or an error occurred */ for (;;) { /* Fetch the current dfa and state */ dfa *d = ps->p_stack.s_top->s_dfa; state *s = &d->d_state[ps->p_stack.s_top->s_state]; D(printf(" DFA '%s', state %d:", d->d_name, ps->p_stack.s_top->s_state)); /* Check accelerator */ if (s->s_lower <= ilabel && ilabel < s->s_upper) { int x = s->s_accel[ilabel - s->s_lower]; if (x != -1) { if (x & (1<<7)) { /* Push non-terminal */ int nt = (x >> 8) + NT_OFFSET; int arrow = x & ((1<<7)-1); dfa *d1 = PyGrammar_FindDFA( ps->p_grammar, nt); if ((err = push(&ps->p_stack, nt, d1, arrow, lineno, col_offset)) > 0) { D(printf(" MemError: push\n")); return err; } D(printf(" Push ...\n")); continue; } /* Shift the token */ if ((err = shift(&ps->p_stack, type, str, x, lineno, col_offset)) > 0) { D(printf(" MemError: shift.\n")); return err; } D(printf(" Shift.\n")); /* Pop while we are in an accept-only state */ while (s = &d->d_state [ps->p_stack.s_top->s_state], s->s_accept && s->s_narcs == 1) { D(printf(" DFA '%s', state %d: " "Direct pop.\n", d->d_name, ps->p_stack.s_top->s_state)); #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif s_pop(&ps->p_stack); if (s_empty(&ps->p_stack)) { D(printf(" ACCEPT.\n")); return E_DONE; } d = ps->p_stack.s_top->s_dfa; } return E_OK; } } if (s->s_accept) { #ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD #if 0 if (d->d_name[0] == 'i' && strcmp(d->d_name, "import_stmt") == 0) future_hack(ps); #endif #endif /* Pop this dfa and try again */ s_pop(&ps->p_stack); D(printf(" Pop ...\n")); if (s_empty(&ps->p_stack)) { D(printf(" Error: bottom of stack.\n")); return E_SYNTAX; } continue; } /* Stuck, report syntax error */ D(printf(" Error.\n")); if (expected_ret) { if (s->s_lower == s->s_upper - 1) { /* Only one possible expected token */ *expected_ret = ps->p_grammar-> g_ll.ll_label[s->s_lower].lb_type; } else *expected_ret = -1; } return E_SYNTAX; } } #ifdef Py_DEBUG /* DEBUG OUTPUT */ void dumptree(grammar *g, node *n) { int i; if (n == NULL) printf("NIL"); else { label l; l.lb_type = TYPE(n); l.lb_str = STR(n); printf("%s", PyGrammar_LabelRepr(&l)); if (ISNONTERMINAL(TYPE(n))) { printf("("); for (i = 0; i < NCH(n); i++) { if (i > 0) printf(","); dumptree(g, CHILD(n, i)); } printf(")"); } } } void showtree(grammar *g, node *n) { int i; if (n == NULL) return; if (ISNONTERMINAL(TYPE(n))) { for (i = 0; i < NCH(n); i++) showtree(g, CHILD(n, i)); } else if (ISTERMINAL(TYPE(n))) { printf("%s", _PyParser_TokenNames[TYPE(n)]); if (TYPE(n) == NUMBER || TYPE(n) == NAME) printf("(%s)", STR(n)); printf(" "); } else printf("? "); } void printtree(parser_state *ps) { if (Py_DebugFlag) { printf("Parse tree:\n"); dumptree(ps->p_grammar, ps->p_tree); printf("\n"); printf("Tokens:\n"); showtree(ps->p_grammar, ps->p_tree); printf("\n"); } printf("Listing:\n"); PyNode_ListTree(ps->p_tree); printf("\n"); } #endif /* Py_DEBUG */
12,839
445
jart/cosmopolitan
false
cosmopolitan/third_party/python/Parser/asdl_c.py
#! /usr/bin/env python """Generate C code from an ASDL description.""" import os, sys import asdl TABSIZE = 4 MAX_COL = 80 def get_c_type(name): """Return a string for the C name of the type. This function special cases the default types provided by asdl. """ if name in asdl.builtin_types: return name else: return "%s_ty" % name def reflow_lines(s, depth): """Reflow the line s indented depth tabs. Return a sequence of lines where no line extends beyond MAX_COL when properly indented. The first line is properly indented based exclusively on depth * TABSIZE. All following lines -- these are the reflowed lines generated by this function -- start at the same column as the first character beyond the opening { in the first line. """ size = MAX_COL - depth * TABSIZE if len(s) < size: return [s] lines = [] cur = s padding = "" while len(cur) > size: i = cur.rfind(' ', 0, size) # XXX this should be fixed for real if i == -1 and 'GeneratorExp' in cur: i = size + 3 assert i != -1, "Impossible line %d to reflow: %r" % (size, s) lines.append(padding + cur[:i]) if len(lines) == 1: # find new size based on brace j = cur.find('{', 0, i) if j >= 0: j += 2 # account for the brace and the space after it size -= j padding = " " * j else: j = cur.find('(', 0, i) if j >= 0: j += 1 # account for the paren (no space after it) size -= j padding = " " * j cur = cur[i+1:] else: lines.append(padding + cur) return lines def is_simple(sum): """Return True if a sum is a simple. A sum is simple if its types have no fields, e.g. unaryop = Invert | Not | UAdd | USub """ for t in sum.types: if t.fields: return False return True class EmitVisitor(asdl.VisitorBase): """Visit that emits lines""" def __init__(self, file): self.file = file self.identifiers = set() super(EmitVisitor, self).__init__() def emit_identifier(self, name): name = str(name) if name in self.identifiers: return self.emit("_Py_IDENTIFIER(%s);" % name, 0) self.identifiers.add(name) def emit(self, s, depth, reflow=True): # XXX reflow long lines? if reflow: lines = reflow_lines(s, depth) else: lines = [s] for line in lines: line = (" " * TABSIZE * depth) + line + "\n" self.file.write(line) class TypeDefVisitor(EmitVisitor): def visitModule(self, mod): for dfn in mod.dfns: self.visit(dfn) def visitType(self, type, depth=0): self.visit(type.value, type.name, depth) def visitSum(self, sum, name, depth): if is_simple(sum): self.simple_sum(sum, name, depth) else: self.sum_with_constructors(sum, name, depth) def simple_sum(self, sum, name, depth): enum = [] for i in range(len(sum.types)): type = sum.types[i] enum.append("%s=%d" % (type.name, i + 1)) enums = ", ".join(enum) ctype = get_c_type(name) s = "typedef enum _%s { %s } %s;" % (name, enums, ctype) self.emit(s, depth) self.emit("", depth) def sum_with_constructors(self, sum, name, depth): ctype = get_c_type(name) s = "typedef struct _%(name)s *%(ctype)s;" % locals() self.emit(s, depth) self.emit("", depth) def visitProduct(self, product, name, depth): ctype = get_c_type(name) s = "typedef struct _%(name)s *%(ctype)s;" % locals() self.emit(s, depth) self.emit("", depth) class StructVisitor(EmitVisitor): """Visitor to generate typedefs for AST.""" def visitModule(self, mod): for dfn in mod.dfns: self.visit(dfn) def visitType(self, type, depth=0): self.visit(type.value, type.name, depth) def visitSum(self, sum, name, depth): if not is_simple(sum): self.sum_with_constructors(sum, name, depth) def sum_with_constructors(self, sum, name, depth): def emit(s, depth=depth): self.emit(s % sys._getframe(1).f_locals, depth) enum = [] for i in range(len(sum.types)): type = sum.types[i] enum.append("%s_kind=%d" % (type.name, i + 1)) emit("enum _%(name)s_kind {" + ", ".join(enum) + "};") emit("struct _%(name)s {") emit("enum _%(name)s_kind kind;", depth + 1) emit("union {", depth + 1) for t in sum.types: self.visit(t, depth + 2) emit("} v;", depth + 1) for field in sum.attributes: # rudimentary attribute handling type = str(field.type) assert type in asdl.builtin_types, type emit("%s %s;" % (type, field.name), depth + 1); emit("};") emit("") def visitConstructor(self, cons, depth): if cons.fields: self.emit("struct {", depth) for f in cons.fields: self.visit(f, depth + 1) self.emit("} %s;" % cons.name, depth) self.emit("", depth) def visitField(self, field, depth): # XXX need to lookup field.type, because it might be something # like a builtin... ctype = get_c_type(field.type) name = field.name if field.seq: if field.type == 'cmpop': self.emit("asdl_int_seq *%(name)s;" % locals(), depth) else: self.emit("asdl_seq *%(name)s;" % locals(), depth) else: self.emit("%(ctype)s %(name)s;" % locals(), depth) def visitProduct(self, product, name, depth): self.emit("struct _%(name)s {" % locals(), depth) for f in product.fields: self.visit(f, depth + 1) for field in product.attributes: # rudimentary attribute handling type = str(field.type) assert type in asdl.builtin_types, type self.emit("%s %s;" % (type, field.name), depth + 1); self.emit("};", depth) self.emit("", depth) class PrototypeVisitor(EmitVisitor): """Generate function prototypes for the .h file""" def visitModule(self, mod): for dfn in mod.dfns: self.visit(dfn) def visitType(self, type): self.visit(type.value, type.name) def visitSum(self, sum, name): if is_simple(sum): pass # XXX else: for t in sum.types: self.visit(t, name, sum.attributes) def get_args(self, fields): """Return list of C argument into, one for each field. Argument info is 3-tuple of a C type, variable name, and flag that is true if type can be NULL. """ args = [] unnamed = {} for f in fields: if f.name is None: name = f.type c = unnamed[name] = unnamed.get(name, 0) + 1 if c > 1: name = "name%d" % (c - 1) else: name = f.name # XXX should extend get_c_type() to handle this if f.seq: if f.type == 'cmpop': ctype = "asdl_int_seq *" else: ctype = "asdl_seq *" else: ctype = get_c_type(f.type) args.append((ctype, name, f.opt or f.seq)) return args def visitConstructor(self, cons, type, attrs): args = self.get_args(cons.fields) attrs = self.get_args(attrs) ctype = get_c_type(type) self.emit_function(cons.name, ctype, args, attrs) def emit_function(self, name, ctype, args, attrs, union=True): args = args + attrs if args: argstr = ", ".join(["%s %s" % (atype, aname) for atype, aname, opt in args]) argstr += ", PyArena *arena" else: argstr = "PyArena *arena" margs = "a0" for i in range(1, len(args)+1): margs += ", a%d" % i self.emit("#define %s(%s) _Py_%s(%s)" % (name, margs, name, margs), 0, reflow=False) self.emit("%s _Py_%s(%s);" % (ctype, name, argstr), False) def visitProduct(self, prod, name): self.emit_function(name, get_c_type(name), self.get_args(prod.fields), self.get_args(prod.attributes), union=False) class FunctionVisitor(PrototypeVisitor): """Visitor to generate constructor functions for AST.""" def emit_function(self, name, ctype, args, attrs, union=True): def emit(s, depth=0, reflow=True): self.emit(s, depth, reflow) argstr = ", ".join(["%s %s" % (atype, aname) for atype, aname, opt in args + attrs]) if argstr: argstr += ", PyArena *arena" else: argstr = "PyArena *arena" self.emit("%s" % ctype, 0) emit("%s(%s)" % (name, argstr)) emit("{") emit("%s p;" % ctype, 1) for argtype, argname, opt in args: if not opt and argtype != "int": emit("if (!%s) {" % argname, 1) emit("PyErr_SetString(PyExc_ValueError,", 2) msg = "field %s is required for %s" % (argname, name) emit(' "%s");' % msg, 2, reflow=False) emit('return NULL;', 2) emit('}', 1) emit("p = (%s)PyArena_Malloc(arena, sizeof(*p));" % ctype, 1); emit("if (!p)", 1) emit("return NULL;", 2) if union: self.emit_body_union(name, args, attrs) else: self.emit_body_struct(name, args, attrs) emit("return p;", 1) emit("}") emit("") def emit_body_union(self, name, args, attrs): def emit(s, depth=0, reflow=True): self.emit(s, depth, reflow) emit("p->kind = %s_kind;" % name, 1) for argtype, argname, opt in args: emit("p->v.%s.%s = %s;" % (name, argname, argname), 1) for argtype, argname, opt in attrs: emit("p->%s = %s;" % (argname, argname), 1) def emit_body_struct(self, name, args, attrs): def emit(s, depth=0, reflow=True): self.emit(s, depth, reflow) for argtype, argname, opt in args: emit("p->%s = %s;" % (argname, argname), 1) for argtype, argname, opt in attrs: emit("p->%s = %s;" % (argname, argname), 1) class PickleVisitor(EmitVisitor): def visitModule(self, mod): for dfn in mod.dfns: self.visit(dfn) def visitType(self, type): self.visit(type.value, type.name) def visitSum(self, sum, name): pass def visitProduct(self, sum, name): pass def visitConstructor(self, cons, name): pass def visitField(self, sum): pass class Obj2ModPrototypeVisitor(PickleVisitor): def visitProduct(self, prod, name): code = "static int obj2ast_%s(PyObject* obj, %s* out, PyArena* arena);" self.emit(code % (name, get_c_type(name)), 0) visitSum = visitProduct class Obj2ModVisitor(PickleVisitor): def funcHeader(self, name): ctype = get_c_type(name) self.emit("int", 0) self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0) self.emit("{", 0) self.emit("int isinstance;", 1) self.emit("", 0) def sumTrailer(self, name, add_label=False): self.emit("", 0) # there's really nothing more we can do if this fails ... error = "expected some sort of %s, but got %%R" % name format = "PyErr_Format(PyExc_TypeError, \"%s\", obj);" self.emit(format % error, 1, reflow=False) if add_label: self.emit("failed:", 1) self.emit("Py_XDECREF(tmp);", 1) self.emit("return 1;", 1) self.emit("}", 0) self.emit("", 0) def simpleSum(self, sum, name): self.funcHeader(name) for t in sum.types: line = ("isinstance = PyObject_IsInstance(obj, " "(PyObject *)%s_type);") self.emit(line % (t.name,), 1) self.emit("if (isinstance == -1) {", 1) self.emit("return 1;", 2) self.emit("}", 1) self.emit("if (isinstance) {", 1) self.emit("*out = %s;" % t.name, 2) self.emit("return 0;", 2) self.emit("}", 1) self.sumTrailer(name) def buildArgs(self, fields): return ", ".join(fields + ["arena"]) def complexSum(self, sum, name): self.funcHeader(name) self.emit("PyObject *tmp = NULL;", 1) for a in sum.attributes: self.visitAttributeDeclaration(a, name, sum=sum) self.emit("", 0) # XXX: should we only do this for 'expr'? self.emit("if (obj == Py_None) {", 1) self.emit("*out = NULL;", 2) self.emit("return 0;", 2) self.emit("}", 1) for a in sum.attributes: self.visitField(a, name, sum=sum, depth=1) for t in sum.types: line = "isinstance = PyObject_IsInstance(obj, (PyObject*)%s_type);" self.emit(line % (t.name,), 1) self.emit("if (isinstance == -1) {", 1) self.emit("return 1;", 2) self.emit("}", 1) self.emit("if (isinstance) {", 1) for f in t.fields: self.visitFieldDeclaration(f, t.name, sum=sum, depth=2) self.emit("", 0) for f in t.fields: self.visitField(f, t.name, sum=sum, depth=2) args = [f.name for f in t.fields] + [a.name for a in sum.attributes] self.emit("*out = %s(%s);" % (t.name, self.buildArgs(args)), 2) self.emit("if (*out == NULL) goto failed;", 2) self.emit("return 0;", 2) self.emit("}", 1) self.sumTrailer(name, True) def visitAttributeDeclaration(self, a, name, sum=sum): ctype = get_c_type(a.type) self.emit("%s %s;" % (ctype, a.name), 1) def visitSum(self, sum, name): if is_simple(sum): self.simpleSum(sum, name) else: self.complexSum(sum, name) def visitProduct(self, prod, name): ctype = get_c_type(name) self.emit("int", 0) self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0) self.emit("{", 0) self.emit("PyObject* tmp = NULL;", 1) for f in prod.fields: self.visitFieldDeclaration(f, name, prod=prod, depth=1) for a in prod.attributes: self.visitFieldDeclaration(a, name, prod=prod, depth=1) self.emit("", 0) for f in prod.fields: self.visitField(f, name, prod=prod, depth=1) for a in prod.attributes: self.visitField(a, name, prod=prod, depth=1) args = [f.name for f in prod.fields] args.extend([a.name for a in prod.attributes]) self.emit("*out = %s(%s);" % (name, self.buildArgs(args)), 1) self.emit("return 0;", 1) self.emit("failed:", 0) self.emit("Py_XDECREF(tmp);", 1) self.emit("return 1;", 1) self.emit("}", 0) self.emit("", 0) def visitFieldDeclaration(self, field, name, sum=None, prod=None, depth=0): ctype = get_c_type(field.type) if field.seq: if self.isSimpleType(field): self.emit("asdl_int_seq* %s;" % field.name, depth) else: self.emit("asdl_seq* %s;" % field.name, depth) else: ctype = get_c_type(field.type) self.emit("%s %s;" % (ctype, field.name), depth) def isSimpleSum(self, field): # XXX can the members of this list be determined automatically? return field.type in ('expr_context', 'boolop', 'operator', 'unaryop', 'cmpop') def isNumeric(self, field): return get_c_type(field.type) in ("int", "bool") def isSimpleType(self, field): return self.isSimpleSum(field) or self.isNumeric(field) def visitField(self, field, name, sum=None, prod=None, depth=0): ctype = get_c_type(field.type) if field.opt: check = "exists_not_none(obj, &PyId_%s)" % (field.name,) else: check = "_PyObject_HasAttrId(obj, &PyId_%s)" % (field.name,) self.emit("if (%s) {" % (check,), depth, reflow=False) self.emit("int res;", depth+1) if field.seq: self.emit("Py_ssize_t len;", depth+1) self.emit("Py_ssize_t i;", depth+1) self.emit("tmp = _PyObject_GetAttrId(obj, &PyId_%s);" % field.name, depth+1) self.emit("if (tmp == NULL) goto failed;", depth+1) if field.seq: self.emit("if (!PyList_Check(tmp)) {", depth+1) self.emit("PyErr_Format(PyExc_TypeError, \"%s field \\\"%s\\\" must " "be a list, not a %%.200s\", tmp->ob_type->tp_name);" % (name, field.name), depth+2, reflow=False) self.emit("goto failed;", depth+2) self.emit("}", depth+1) self.emit("len = PyList_GET_SIZE(tmp);", depth+1) if self.isSimpleType(field): self.emit("%s = _Py_asdl_int_seq_new(len, arena);" % field.name, depth+1) else: self.emit("%s = _Py_asdl_seq_new(len, arena);" % field.name, depth+1) self.emit("if (%s == NULL) goto failed;" % field.name, depth+1) self.emit("for (i = 0; i < len; i++) {", depth+1) self.emit("%s val;" % ctype, depth+2) self.emit("res = obj2ast_%s(PyList_GET_ITEM(tmp, i), &val, arena);" % field.type, depth+2, reflow=False) self.emit("if (res != 0) goto failed;", depth+2) self.emit("if (len != PyList_GET_SIZE(tmp)) {", depth+2) self.emit("PyErr_SetString(PyExc_RuntimeError, \"%s field \\\"%s\\\" " "changed size during iteration\");" % (name, field.name), depth+3, reflow=False) self.emit("goto failed;", depth+3) self.emit("}", depth+2) self.emit("asdl_seq_SET(%s, i, val);" % field.name, depth+2) self.emit("}", depth+1) else: self.emit("res = obj2ast_%s(tmp, &%s, arena);" % (field.type, field.name), depth+1) self.emit("if (res != 0) goto failed;", depth+1) self.emit("Py_CLEAR(tmp);", depth+1) self.emit("} else {", depth) if not field.opt: message = "required field \\\"%s\\\" missing from %s" % (field.name, name) format = "PyErr_SetString(PyExc_TypeError, \"%s\");" self.emit(format % message, depth+1, reflow=False) self.emit("return 1;", depth+1) else: if self.isNumeric(field): self.emit("%s = 0;" % field.name, depth+1) elif not self.isSimpleType(field): self.emit("%s = NULL;" % field.name, depth+1) else: raise TypeError("could not determine the default value for %s" % field.name) self.emit("}", depth) class MarshalPrototypeVisitor(PickleVisitor): def prototype(self, sum, name): ctype = get_c_type(name) self.emit("static int marshal_write_%s(PyObject **, int *, %s);" % (name, ctype), 0) visitProduct = visitSum = prototype class PyTypesDeclareVisitor(PickleVisitor): def visitProduct(self, prod, name): self.emit("static PyTypeObject *%s_type;" % name, 0) self.emit("static PyObject* ast2obj_%s(void*);" % name, 0) if prod.attributes: for a in prod.attributes: self.emit_identifier(a.name) self.emit("static char *%s_attributes[] = {" % name, 0) for a in prod.attributes: self.emit('"%s",' % a.name, 1) self.emit("};", 0) if prod.fields: for f in prod.fields: self.emit_identifier(f.name) self.emit("static char *%s_fields[]={" % name,0) for f in prod.fields: self.emit('"%s",' % f.name, 1) self.emit("};", 0) def visitSum(self, sum, name): self.emit("static PyTypeObject *%s_type;" % name, 0) if sum.attributes: for a in sum.attributes: self.emit_identifier(a.name) self.emit("static char *%s_attributes[] = {" % name, 0) for a in sum.attributes: self.emit('"%s",' % a.name, 1) self.emit("};", 0) ptype = "void*" if is_simple(sum): ptype = get_c_type(name) tnames = [] for t in sum.types: tnames.append(str(t.name)+"_singleton") tnames = ", *".join(tnames) self.emit("static PyObject *%s;" % tnames, 0) self.emit("static PyObject* ast2obj_%s(%s);" % (name, ptype), 0) for t in sum.types: self.visitConstructor(t, name) def visitConstructor(self, cons, name): self.emit("static PyTypeObject *%s_type;" % cons.name, 0) if cons.fields: for t in cons.fields: self.emit_identifier(t.name) self.emit("static char *%s_fields[]={" % cons.name, 0) for t in cons.fields: self.emit('"%s",' % t.name, 1) self.emit("};",0) class PyTypesVisitor(PickleVisitor): def visitModule(self, mod): self.emit(""" typedef struct { PyObject_HEAD PyObject *dict; } AST_object; static void ast_dealloc(AST_object *self) { /* bpo-31095: UnTrack is needed before calling any callbacks */ PyObject_GC_UnTrack(self); Py_CLEAR(self->dict); Py_TYPE(self)->tp_free(self); } static int ast_traverse(AST_object *self, visitproc visit, void *arg) { Py_VISIT(self->dict); return 0; } static int ast_clear(AST_object *self) { Py_CLEAR(self->dict); return 0; } static int ast_type_init(PyObject *self, PyObject *args, PyObject *kw) { _Py_IDENTIFIER(_fields); Py_ssize_t i, numfields = 0; int res = -1; PyObject *key, *value, *fields; fields = _PyObject_GetAttrId((PyObject*)Py_TYPE(self), &PyId__fields); if (!fields) PyErr_Clear(); if (fields) { numfields = PySequence_Size(fields); if (numfields == -1) goto cleanup; } res = 0; /* if no error occurs, this stays 0 to the end */ if (PyTuple_GET_SIZE(args) > 0) { if (numfields != PyTuple_GET_SIZE(args)) { PyErr_Format(PyExc_TypeError, "%.400s constructor takes %s" "%zd positional argument%s", Py_TYPE(self)->tp_name, numfields == 0 ? "" : "either 0 or ", numfields, numfields == 1 ? "" : "s"); res = -1; goto cleanup; } for (i = 0; i < PyTuple_GET_SIZE(args); i++) { /* cannot be reached when fields is NULL */ PyObject *name = PySequence_GetItem(fields, i); if (!name) { res = -1; goto cleanup; } res = PyObject_SetAttr(self, name, PyTuple_GET_ITEM(args, i)); Py_DECREF(name); if (res < 0) goto cleanup; } } if (kw) { i = 0; /* needed by PyDict_Next */ while (PyDict_Next(kw, &i, &key, &value)) { res = PyObject_SetAttr(self, key, value); if (res < 0) goto cleanup; } } cleanup: Py_XDECREF(fields); return res; } /* Pickling support */ static PyObject * ast_type_reduce(PyObject *self, PyObject *unused) { PyObject *res; _Py_IDENTIFIER(__dict__); PyObject *dict = _PyObject_GetAttrId(self, &PyId___dict__); if (dict == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) PyErr_Clear(); else return NULL; } if (dict) { res = Py_BuildValue("O()O", Py_TYPE(self), dict); Py_DECREF(dict); return res; } return Py_BuildValue("O()", Py_TYPE(self)); } static PyMethodDef ast_type_methods[] = { {"__reduce__", ast_type_reduce, METH_NOARGS, NULL}, {NULL} }; static PyGetSetDef ast_type_getsets[] = { {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict}, {NULL} }; static PyTypeObject AST_type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "_ast.AST", sizeof(AST_object), 0, (destructor)ast_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)ast_traverse, /* tp_traverse */ (inquiry)ast_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ast_type_methods, /* tp_methods */ 0, /* tp_members */ ast_type_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(AST_object, dict),/* tp_dictoffset */ (initproc)ast_type_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; static PyTypeObject* make_type(char *type, PyTypeObject* base, char**fields, int num_fields) { PyObject *fnames, *result; int i; fnames = PyTuple_New(num_fields); if (!fnames) return NULL; for (i = 0; i < num_fields; i++) { PyObject *field = PyUnicode_FromString(fields[i]); if (!field) { Py_DECREF(fnames); return NULL; } PyTuple_SET_ITEM(fnames, i, field); } result = PyObject_CallFunction((PyObject*)&PyType_Type, "s(O){sOss}", type, base, "_fields", fnames, "__module__", "_ast"); Py_DECREF(fnames); return (PyTypeObject*)result; } static int add_attributes(PyTypeObject* type, char**attrs, int num_fields) { int i, result; _Py_IDENTIFIER(_attributes); PyObject *s, *l = PyTuple_New(num_fields); if (!l) return 0; for (i = 0; i < num_fields; i++) { s = PyUnicode_FromString(attrs[i]); if (!s) { Py_DECREF(l); return 0; } PyTuple_SET_ITEM(l, i, s); } result = _PyObject_SetAttrId((PyObject*)type, &PyId__attributes, l) >= 0; Py_DECREF(l); return result; } /* Conversion AST -> Python */ static PyObject* ast2obj_list(asdl_seq *seq, PyObject* (*func)(void*)) { Py_ssize_t i, n = asdl_seq_LEN(seq); PyObject *result = PyList_New(n); PyObject *value; if (!result) return NULL; for (i = 0; i < n; i++) { value = func(asdl_seq_GET(seq, i)); if (!value) { Py_DECREF(result); return NULL; } PyList_SET_ITEM(result, i, value); } return result; } static PyObject* ast2obj_object(void *o) { if (!o) o = Py_None; Py_INCREF((PyObject*)o); return (PyObject*)o; } #define ast2obj_singleton ast2obj_object #define ast2obj_constant ast2obj_object #define ast2obj_identifier ast2obj_object #define ast2obj_string ast2obj_object #define ast2obj_bytes ast2obj_object static PyObject* ast2obj_int(long b) { return PyLong_FromLong(b); } /* Conversion Python -> AST */ static int obj2ast_singleton(PyObject *obj, PyObject** out, PyArena* arena) { if (obj != Py_None && obj != Py_True && obj != Py_False) { PyErr_SetString(PyExc_ValueError, "AST singleton must be True, False, or None"); return 1; } *out = obj; return 0; } static int obj2ast_object(PyObject* obj, PyObject** out, PyArena* arena) { if (obj == Py_None) obj = NULL; if (obj) { if (PyArena_AddPyObject(arena, obj) < 0) { *out = NULL; return -1; } Py_INCREF(obj); } *out = obj; return 0; } static int obj2ast_constant(PyObject* obj, PyObject** out, PyArena* arena) { if (obj) { if (PyArena_AddPyObject(arena, obj) < 0) { *out = NULL; return -1; } Py_INCREF(obj); } *out = obj; return 0; } static int obj2ast_identifier(PyObject* obj, PyObject** out, PyArena* arena) { if (!PyUnicode_CheckExact(obj) && obj != Py_None) { PyErr_SetString(PyExc_TypeError, "AST identifier must be of type str"); return 1; } return obj2ast_object(obj, out, arena); } static int obj2ast_string(PyObject* obj, PyObject** out, PyArena* arena) { if (!PyUnicode_CheckExact(obj) && !PyBytes_CheckExact(obj)) { PyErr_SetString(PyExc_TypeError, "AST string must be of type str"); return 1; } return obj2ast_object(obj, out, arena); } static int obj2ast_bytes(PyObject* obj, PyObject** out, PyArena* arena) { if (!PyBytes_CheckExact(obj)) { PyErr_SetString(PyExc_TypeError, "AST bytes must be of type bytes"); return 1; } return obj2ast_object(obj, out, arena); } static int obj2ast_int(PyObject* obj, int* out, PyArena* arena) { int i; if (!PyLong_Check(obj)) { PyErr_Format(PyExc_ValueError, "invalid integer value: %R", obj); return 1; } i = _PyLong_AsInt(obj); if (i == -1 && PyErr_Occurred()) return 1; *out = i; return 0; } static int add_ast_fields(void) { PyObject *empty_tuple, *d; if (PyType_Ready(&AST_type) < 0) return -1; d = AST_type.tp_dict; empty_tuple = PyTuple_New(0); if (!empty_tuple || PyDict_SetItemString(d, "_fields", empty_tuple) < 0 || PyDict_SetItemString(d, "_attributes", empty_tuple) < 0) { Py_XDECREF(empty_tuple); return -1; } Py_DECREF(empty_tuple); return 0; } static int exists_not_none(PyObject *obj, _Py_Identifier *id) { int isnone; PyObject *attr = _PyObject_GetAttrId(obj, id); if (!attr) { PyErr_Clear(); return 0; } isnone = attr == Py_None; Py_DECREF(attr); return !isnone; } """, 0, reflow=False) self.emit("static int init_types(void)",0) self.emit("{", 0) self.emit("static int initialized;", 1) self.emit("if (initialized) return 1;", 1) self.emit("if (add_ast_fields() < 0) return 0;", 1) for dfn in mod.dfns: self.visit(dfn) self.emit("initialized = 1;", 1) self.emit("return 1;", 1); self.emit("}", 0) def visitProduct(self, prod, name): if prod.fields: fields = name+"_fields" else: fields = "NULL" self.emit('%s_type = make_type("%s", &AST_type, %s, %d);' % (name, name, fields, len(prod.fields)), 1) self.emit("if (!%s_type) return 0;" % name, 1) if prod.attributes: self.emit("if (!add_attributes(%s_type, %s_attributes, %d)) return 0;" % (name, name, len(prod.attributes)), 1) else: self.emit("if (!add_attributes(%s_type, NULL, 0)) return 0;" % name, 1) def visitSum(self, sum, name): self.emit('%s_type = make_type("%s", &AST_type, NULL, 0);' % (name, name), 1) self.emit("if (!%s_type) return 0;" % name, 1) if sum.attributes: self.emit("if (!add_attributes(%s_type, %s_attributes, %d)) return 0;" % (name, name, len(sum.attributes)), 1) else: self.emit("if (!add_attributes(%s_type, NULL, 0)) return 0;" % name, 1) simple = is_simple(sum) for t in sum.types: self.visitConstructor(t, name, simple) def visitConstructor(self, cons, name, simple): if cons.fields: fields = cons.name+"_fields" else: fields = "NULL" self.emit('%s_type = make_type("%s", %s_type, %s, %d);' % (cons.name, cons.name, name, fields, len(cons.fields)), 1) self.emit("if (!%s_type) return 0;" % cons.name, 1) if simple: self.emit("%s_singleton = PyType_GenericNew(%s_type, NULL, NULL);" % (cons.name, cons.name), 1) self.emit("if (!%s_singleton) return 0;" % cons.name, 1) class ASTModuleVisitor(PickleVisitor): def visitModule(self, mod): self.emit("static struct PyModuleDef _astmodule = {", 0) self.emit(' PyModuleDef_HEAD_INIT, "_ast"', 0) self.emit("};", 0) self.emit("PyMODINIT_FUNC", 0) self.emit("PyInit__ast(void)", 0) self.emit("{", 0) self.emit("PyObject *m, *d;", 1) self.emit("if (!init_types()) return NULL;", 1) self.emit('m = PyModule_Create(&_astmodule);', 1) self.emit("if (!m) return NULL;", 1) self.emit("d = PyModule_GetDict(m);", 1) self.emit('if (PyDict_SetItemString(d, "AST", (PyObject*)&AST_type) < 0) return NULL;', 1) self.emit('if (PyModule_AddIntMacro(m, PyCF_ONLY_AST) < 0)', 1) self.emit("return NULL;", 2) for dfn in mod.dfns: self.visit(dfn) self.emit("return m;", 1) self.emit("}", 0) def visitProduct(self, prod, name): self.addObj(name) def visitSum(self, sum, name): self.addObj(name) for t in sum.types: self.visitConstructor(t, name) def visitConstructor(self, cons, name): self.addObj(cons.name) def addObj(self, name): self.emit('if (PyDict_SetItemString(d, "%s", (PyObject*)%s_type) < 0) return NULL;' % (name, name), 1) _SPECIALIZED_SEQUENCES = ('stmt', 'expr') def find_sequence(fields, doing_specialization): """Return True if any field uses a sequence.""" for f in fields: if f.seq: if not doing_specialization: return True if str(f.type) not in _SPECIALIZED_SEQUENCES: return True return False def has_sequence(types, doing_specialization): for t in types: if find_sequence(t.fields, doing_specialization): return True return False class StaticVisitor(PickleVisitor): CODE = '''Very simple, always emit this static code. Override CODE''' def visit(self, object): self.emit(self.CODE, 0, reflow=False) class ObjVisitor(PickleVisitor): def func_begin(self, name): ctype = get_c_type(name) self.emit("PyObject*", 0) self.emit("ast2obj_%s(void* _o)" % (name), 0) self.emit("{", 0) self.emit("%s o = (%s)_o;" % (ctype, ctype), 1) self.emit("PyObject *result = NULL, *value = NULL;", 1) self.emit('if (!o) {', 1) self.emit("Py_INCREF(Py_None);", 2) self.emit('return Py_None;', 2) self.emit("}", 1) self.emit('', 0) def func_end(self): self.emit("return result;", 1) self.emit("failed:", 0) self.emit("Py_XDECREF(value);", 1) self.emit("Py_XDECREF(result);", 1) self.emit("return NULL;", 1) self.emit("}", 0) self.emit("", 0) def visitSum(self, sum, name): if is_simple(sum): self.simpleSum(sum, name) return self.func_begin(name) self.emit("switch (o->kind) {", 1) for i in range(len(sum.types)): t = sum.types[i] self.visitConstructor(t, i + 1, name) self.emit("}", 1) for a in sum.attributes: self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1) self.emit("if (!value) goto failed;", 1) self.emit('if (_PyObject_SetAttrId(result, &PyId_%s, value) < 0)' % a.name, 1) self.emit('goto failed;', 2) self.emit('Py_DECREF(value);', 1) self.func_end() def simpleSum(self, sum, name): self.emit("PyObject* ast2obj_%s(%s_ty o)" % (name, name), 0) self.emit("{", 0) self.emit("switch(o) {", 1) for t in sum.types: self.emit("case %s:" % t.name, 2) self.emit("Py_INCREF(%s_singleton);" % t.name, 3) self.emit("return %s_singleton;" % t.name, 3) self.emit("default:", 2) self.emit('/* should never happen, but just in case ... */', 3) code = "PyErr_Format(PyExc_SystemError, \"unknown %s found\");" % name self.emit(code, 3, reflow=False) self.emit("return NULL;", 3) self.emit("}", 1) self.emit("}", 0) def visitProduct(self, prod, name): self.func_begin(name) self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % name, 1); self.emit("if (!result) return NULL;", 1) for field in prod.fields: self.visitField(field, name, 1, True) for a in prod.attributes: self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1) self.emit("if (!value) goto failed;", 1) self.emit('if (_PyObject_SetAttrId(result, &PyId_%s, value) < 0)' % a.name, 1) self.emit('goto failed;', 2) self.emit('Py_DECREF(value);', 1) self.func_end() def visitConstructor(self, cons, enum, name): self.emit("case %s_kind:" % cons.name, 1) self.emit("result = PyType_GenericNew(%s_type, NULL, NULL);" % cons.name, 2); self.emit("if (!result) goto failed;", 2) for f in cons.fields: self.visitField(f, cons.name, 2, False) self.emit("break;", 2) def visitField(self, field, name, depth, product): def emit(s, d): self.emit(s, depth + d) if product: value = "o->%s" % field.name else: value = "o->v.%s.%s" % (name, field.name) self.set(field, value, depth) emit("if (!value) goto failed;", 0) emit('if (_PyObject_SetAttrId(result, &PyId_%s, value) == -1)' % field.name, 0) emit("goto failed;", 1) emit("Py_DECREF(value);", 0) def emitSeq(self, field, value, depth, emit): emit("seq = %s;" % value, 0) emit("n = asdl_seq_LEN(seq);", 0) emit("value = PyList_New(n);", 0) emit("if (!value) goto failed;", 0) emit("for (i = 0; i < n; i++) {", 0) self.set("value", field, "asdl_seq_GET(seq, i)", depth + 1) emit("if (!value1) goto failed;", 1) emit("PyList_SET_ITEM(value, i, value1);", 1) emit("value1 = NULL;", 1) emit("}", 0) def set(self, field, value, depth): if field.seq: # XXX should really check for is_simple, but that requires a symbol table if field.type == "cmpop": # While the sequence elements are stored as void*, # ast2obj_cmpop expects an enum self.emit("{", depth) self.emit("Py_ssize_t i, n = asdl_seq_LEN(%s);" % value, depth+1) self.emit("value = PyList_New(n);", depth+1) self.emit("if (!value) goto failed;", depth+1) self.emit("for(i = 0; i < n; i++)", depth+1) # This cannot fail, so no need for error handling self.emit("PyList_SET_ITEM(value, i, ast2obj_cmpop((cmpop_ty)asdl_seq_GET(%s, i)));" % value, depth+2, reflow=False) self.emit("}", depth) else: self.emit("value = ast2obj_list(%s, ast2obj_%s);" % (value, field.type), depth) else: ctype = get_c_type(field.type) self.emit("value = ast2obj_%s(%s);" % (field.type, value), depth, reflow=False) class PartingShots(StaticVisitor): CODE = """ PyObject* PyAST_mod2obj(mod_ty t) { if (!init_types()) return NULL; return ast2obj_mod(t); } /* mode is 0 for "exec", 1 for "eval" and 2 for "single" input */ mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode) { mod_ty res; PyObject *req_type[3]; char *req_name[] = {"Module", "Expression", "Interactive"}; int isinstance; req_type[0] = (PyObject*)Module_type; req_type[1] = (PyObject*)Expression_type; req_type[2] = (PyObject*)Interactive_type; assert(0 <= mode && mode <= 2); if (!init_types()) return NULL; isinstance = PyObject_IsInstance(ast, req_type[mode]); if (isinstance == -1) return NULL; if (!isinstance) { PyErr_Format(PyExc_TypeError, "expected %s node, got %.400s", req_name[mode], Py_TYPE(ast)->tp_name); return NULL; } if (obj2ast_mod(ast, &res, arena) != 0) return NULL; else return res; } int PyAST_Check(PyObject* obj) { if (!init_types()) return -1; return PyObject_IsInstance(obj, (PyObject*)&AST_type); } """ class ChainOfVisitors: def __init__(self, *visitors): self.visitors = visitors def visit(self, object): for v in self.visitors: v.visit(object) v.emit("", 0) def main(srcfile, dump_module=False): argv0 = sys.argv[0] components = argv0.split(os.sep) argv0 = os.sep.join(components[-2:]) mod = asdl.parse(srcfile) if dump_module: print('Parsed Module:') print(mod) if not asdl.check(mod): sys.exit(1) if H_FILE: with open(H_FILE, "w") as f: f.write("\ #ifndef COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_PYTHON_AST_H_\n\ #define COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_PYTHON_AST_H_\n\ #include \"third_party/python/Include/asdl.h\"\n\ #if !(__ASSEMBLER__ + __LINKER__ + 0)\n\ COSMOPOLITAN_C_START_\n\ /* clang-format off */\n\ /* File automatically generated by %s. */\n\ \n\ " % argv0) c = ChainOfVisitors(TypeDefVisitor(f), StructVisitor(f), PrototypeVisitor(f), ) c.visit(mod) f.write("\ PyObject* PyAST_mod2obj(mod_ty t);\n\ mod_ty PyAST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n\ int PyAST_Check(PyObject* obj);\n\ \n\ COSMOPOLITAN_C_END_\n\ #endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */\n\ #endif /* COSMOPOLITAN_THIRD_PARTY_PYTHON_INCLUDE_PYTHON_AST_H_ */\n") if C_FILE: with open(C_FILE, "w") as f: f.write('\ #include "third_party/python/Include/%s-ast.h"\n\ #include "third_party/python/Include/abstract.h"\n\ #include "third_party/python/Include/boolobject.h"\n\ #include "third_party/python/Include/descrobject.h"\n\ #include "third_party/python/Include/dictobject.h"\n\ #include "third_party/python/Include/listobject.h"\n\ #include "third_party/python/Include/longobject.h"\n\ #include "third_party/python/Include/modsupport.h"\n\ #include "third_party/python/Include/object.h"\n\ #include "third_party/python/Include/objimpl.h"\n\ #include "third_party/python/Include/pyerrors.h"\n\ #include "third_party/python/Include/pythonrun.h"\n\ #include "third_party/python/Include/tupleobject.h"\n\ #include "third_party/python/Include/yoink.h"\n\ /* clang-format off */\n\ \n\ PYTHON_PROVIDE("_ast");\n\ \n\ /* File automatically generated by %s. */\n\ \n\ static PyTypeObject AST_type;\n\ ' % (mod.name, argv0)) v = ChainOfVisitors( PyTypesDeclareVisitor(f), PyTypesVisitor(f), Obj2ModPrototypeVisitor(f), FunctionVisitor(f), ObjVisitor(f), Obj2ModVisitor(f), ASTModuleVisitor(f), PartingShots(f), ) v.visit(mod) if __name__ == "__main__": import getopt H_FILE = '' C_FILE = '' dump_module = False opts, args = getopt.getopt(sys.argv[1:], "dh:c:") for o, v in opts: if o == '-h': H_FILE = v if o == '-c': C_FILE = v if o == '-d': dump_module = True if H_FILE and C_FILE: print('Must specify exactly one output file') sys.exit(1) elif len(args) != 1: print('Must specify single input file') sys.exit(1) main(args[0], dump_module)
45,630
1,367
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/structmember.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/warnings.h" /* clang-format off */ /* Map C struct members to Python object attributes */ PyObject * PyMember_GetOne(const char *addr, PyMemberDef *l) { PyObject *v; addr += l->offset; switch (l->type) { case T_BOOL: v = PyBool_FromLong(*(char*)addr); break; case T_BYTE: v = PyLong_FromLong(*(char*)addr); break; case T_UBYTE: v = PyLong_FromUnsignedLong(*(unsigned char*)addr); break; case T_SHORT: v = PyLong_FromLong(*(short*)addr); break; case T_USHORT: v = PyLong_FromUnsignedLong(*(unsigned short*)addr); break; case T_INT: v = PyLong_FromLong(*(int*)addr); break; case T_UINT: v = PyLong_FromUnsignedLong(*(unsigned int*)addr); break; case T_LONG: v = PyLong_FromLong(*(long*)addr); break; case T_ULONG: v = PyLong_FromUnsignedLong(*(unsigned long*)addr); break; case T_PYSSIZET: v = PyLong_FromSsize_t(*(Py_ssize_t*)addr); break; case T_FLOAT: v = PyFloat_FromDouble((double)*(float*)addr); break; case T_DOUBLE: v = PyFloat_FromDouble(*(double*)addr); break; case T_STRING: if (*(char**)addr == NULL) { Py_INCREF(Py_None); v = Py_None; } else v = PyUnicode_FromString(*(char**)addr); break; case T_STRING_INPLACE: v = PyUnicode_FromString((char*)addr); break; case T_CHAR: v = PyUnicode_FromStringAndSize((char*)addr, 1); break; case T_OBJECT: v = *(PyObject **)addr; if (v == NULL) v = Py_None; Py_INCREF(v); break; case T_OBJECT_EX: v = *(PyObject **)addr; if (v == NULL) PyErr_SetString(PyExc_AttributeError, l->name); Py_XINCREF(v); break; case T_LONGLONG: v = PyLong_FromLongLong(*(long long *)addr); break; case T_ULONGLONG: v = PyLong_FromUnsignedLongLong(*(unsigned long long *)addr); break; case T_NONE: v = Py_None; Py_INCREF(v); break; default: PyErr_SetString(PyExc_SystemError, "bad memberdescr type"); v = NULL; } return v; } #define WARN(msg) \ do { \ if (PyErr_WarnEx(PyExc_RuntimeWarning, msg, 1) < 0) \ return -1; \ } while (0) int PyMember_SetOne(char *addr, PyMemberDef *l, PyObject *v) { PyObject *oldv; addr += l->offset; if ((l->flags & READONLY)) { PyErr_SetString(PyExc_AttributeError, "readonly attribute"); return -1; } if (v == NULL) { if (l->type == T_OBJECT_EX) { /* Check if the attribute is set. */ if (*(PyObject **)addr == NULL) { PyErr_SetString(PyExc_AttributeError, l->name); return -1; } } else if (l->type != T_OBJECT) { PyErr_SetString(PyExc_TypeError, "can't delete numeric/char attribute"); return -1; } } switch (l->type) { case T_BOOL:{ if (!PyBool_Check(v)) { PyErr_SetString(PyExc_TypeError, "attribute value type must be bool"); return -1; } if (v == Py_True) *(char*)addr = (char) 1; else *(char*)addr = (char) 0; break; } case T_BYTE:{ long long_val = PyLong_AsLong(v); if ((long_val == -1) && PyErr_Occurred()) return -1; *(char*)addr = (char)long_val; /* XXX: For compatibility, only warn about truncations for now. */ if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN)) WARN("Truncation of value to char"); break; } case T_UBYTE:{ long long_val = PyLong_AsLong(v); if ((long_val == -1) && PyErr_Occurred()) return -1; *(unsigned char*)addr = (unsigned char)long_val; if ((long_val > UCHAR_MAX) || (long_val < 0)) WARN("Truncation of value to unsigned char"); break; } case T_SHORT:{ long long_val = PyLong_AsLong(v); if ((long_val == -1) && PyErr_Occurred()) return -1; *(short*)addr = (short)long_val; if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN)) WARN("Truncation of value to short"); break; } case T_USHORT:{ long long_val = PyLong_AsLong(v); if ((long_val == -1) && PyErr_Occurred()) return -1; *(unsigned short*)addr = (unsigned short)long_val; if ((long_val > USHRT_MAX) || (long_val < 0)) WARN("Truncation of value to unsigned short"); break; } case T_INT:{ long long_val = PyLong_AsLong(v); if ((long_val == -1) && PyErr_Occurred()) return -1; *(int *)addr = (int)long_val; if ((long_val > INT_MAX) || (long_val < INT_MIN)) WARN("Truncation of value to int"); break; } case T_UINT:{ unsigned long ulong_val = PyLong_AsUnsignedLong(v); if ((ulong_val == (unsigned long)-1) && PyErr_Occurred()) { /* XXX: For compatibility, accept negative int values as well. */ PyErr_Clear(); ulong_val = PyLong_AsLong(v); if ((ulong_val == (unsigned long)-1) && PyErr_Occurred()) return -1; *(unsigned int *)addr = (unsigned int)ulong_val; WARN("Writing negative value into unsigned field"); } else *(unsigned int *)addr = (unsigned int)ulong_val; if (ulong_val > UINT_MAX) WARN("Truncation of value to unsigned int"); break; } case T_LONG:{ *(long*)addr = PyLong_AsLong(v); if ((*(long*)addr == -1) && PyErr_Occurred()) return -1; break; } case T_ULONG:{ *(unsigned long*)addr = PyLong_AsUnsignedLong(v); if ((*(unsigned long*)addr == (unsigned long)-1) && PyErr_Occurred()) { /* XXX: For compatibility, accept negative int values as well. */ PyErr_Clear(); *(unsigned long*)addr = PyLong_AsLong(v); if ((*(unsigned long*)addr == (unsigned long)-1) && PyErr_Occurred()) return -1; WARN("Writing negative value into unsigned field"); } break; } case T_PYSSIZET:{ *(Py_ssize_t*)addr = PyLong_AsSsize_t(v); if ((*(Py_ssize_t*)addr == (Py_ssize_t)-1) && PyErr_Occurred()) return -1; break; } case T_FLOAT:{ double double_val = PyFloat_AsDouble(v); if ((double_val == -1) && PyErr_Occurred()) return -1; *(float*)addr = (float)double_val; break; } case T_DOUBLE: *(double*)addr = PyFloat_AsDouble(v); if ((*(double*)addr == -1) && PyErr_Occurred()) return -1; break; case T_OBJECT: case T_OBJECT_EX: Py_XINCREF(v); oldv = *(PyObject **)addr; *(PyObject **)addr = v; Py_XDECREF(oldv); break; case T_CHAR: { char *string; Py_ssize_t len; string = PyUnicode_AsUTF8AndSize(v, &len); if (string == NULL || len != 1) { PyErr_BadArgument(); return -1; } *(char*)addr = string[0]; break; } case T_STRING: case T_STRING_INPLACE: PyErr_SetString(PyExc_TypeError, "readonly attribute"); return -1; case T_LONGLONG:{ long long value; *(long long*)addr = value = PyLong_AsLongLong(v); if ((value == -1) && PyErr_Occurred()) return -1; break; } case T_ULONGLONG:{ unsigned long long value; /* ??? PyLong_AsLongLong accepts an int, but PyLong_AsUnsignedLongLong doesn't ??? */ if (PyLong_Check(v)) *(unsigned long long*)addr = value = PyLong_AsUnsignedLongLong(v); else *(unsigned long long*)addr = value = PyLong_AsLong(v); if ((value == (unsigned long long)-1) && PyErr_Occurred()) return -1; break; } default: PyErr_Format(PyExc_SystemError, "bad memberdescr type for %s", l->name); return -1; } return 0; }
9,924
303
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/compile.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/ast.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/opcode.h" #include "third_party/python/Include/pycapsule.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/symtable.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/warnings.h" #include "third_party/python/Python/wordcode_helpers.inc" /* clang-format off */ /* * This file compiles an abstract syntax tree (AST) into Python bytecode. * * The primary entry point is PyAST_Compile(), which returns a * PyCodeObject. The compiler makes several passes to build the code * object: * 1. Checks for future statements. See future.c * 2. Builds a symbol table. See symtable.c. * 3. Generate code for basic blocks. See compiler_mod() in this file. * 4. Assemble the basic blocks into final code. See assemble() in * this file. * 5. Optimize the byte code (peephole optimizations). See peephole.c * * Note that compiler_mod() suggests module, but the module ast type * (mod_ty) has cases for expressions and interactive statements. * * CAUTION: The VISIT_* macros abort the current function when they * encounter a problem. So don't invoke them when there is memory * which needs to be released. Code blocks are OK, as the compiler * structure takes care of releasing those. Use the arena to manage * objects. */ #define DEFAULT_BLOCK_SIZE 16 #define DEFAULT_BLOCKS 8 #define DEFAULT_CODE_SIZE 128 #define DEFAULT_LNOTAB_SIZE 16 #define COMP_GENEXP 0 #define COMP_LISTCOMP 1 #define COMP_SETCOMP 2 #define COMP_DICTCOMP 3 struct instr { unsigned i_jabs : 1; unsigned i_jrel : 1; unsigned char i_opcode; int i_oparg; struct basicblock_ *i_target; /* target block (if jump instruction) */ int i_lineno; }; typedef struct basicblock_ { /* Each basicblock in a compilation unit is linked via b_list in the reverse order that the block are allocated. b_list points to the next block, not to be confused with b_next, which is next by control flow. */ struct basicblock_ *b_list; /* number of instructions used */ int b_iused; /* length of instruction array (b_instr) */ int b_ialloc; /* pointer to an array of instructions, initially NULL */ struct instr *b_instr; /* If b_next is non-NULL, it is a pointer to the next block reached by normal control flow. */ struct basicblock_ *b_next; /* b_seen is used to perform a DFS of basicblocks. */ unsigned b_seen : 1; /* b_return is true if a RETURN_VALUE opcode is inserted. */ unsigned b_return : 1; /* depth of stack upon entry of block, computed by stackdepth() */ int b_startdepth; /* instruction offset for block, computed by assemble_jump_offsets() */ int b_offset; } basicblock; /* fblockinfo tracks the current frame block. A frame block is used to handle loops, try/except, and try/finally. It's called a frame block to distinguish it from a basic block in the compiler IR. */ enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END }; struct fblockinfo { enum fblocktype fb_type; basicblock *fb_block; }; enum { COMPILER_SCOPE_MODULE, COMPILER_SCOPE_CLASS, COMPILER_SCOPE_FUNCTION, COMPILER_SCOPE_ASYNC_FUNCTION, COMPILER_SCOPE_LAMBDA, COMPILER_SCOPE_COMPREHENSION, }; /* The following items change on entry and exit of code blocks. They must be saved and restored when returning to a block. */ struct compiler_unit { PySTEntryObject *u_ste; PyObject *u_name; PyObject *u_qualname; /* dot-separated qualified name (lazy) */ int u_scope_type; /* The following fields are dicts that map objects to the index of them in co_XXX. The index is used as the argument for opcodes that refer to those collections. */ PyObject *u_consts; /* all constants */ PyObject *u_names; /* all names */ PyObject *u_varnames; /* local variables */ PyObject *u_cellvars; /* cell variables */ PyObject *u_freevars; /* free variables */ PyObject *u_private; /* for private name mangling */ Py_ssize_t u_argcount; /* number of arguments for block */ Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */ /* Pointer to the most recently allocated block. By following b_list members, you can reach all early allocated blocks. */ basicblock *u_blocks; basicblock *u_curblock; /* pointer to current block */ int u_nfblocks; struct fblockinfo u_fblock[CO_MAXBLOCKS]; int u_firstlineno; /* the first lineno of the block */ int u_lineno; /* the lineno for the current stmt */ int u_col_offset; /* the offset of the current stmt */ int u_lineno_set; /* boolean to indicate whether instr has been generated with current lineno */ }; /* This struct captures the global state of a compilation. The u pointer points to the current compilation unit, while units for enclosing blocks are stored in c_stack. The u and c_stack are managed by compiler_enter_scope() and compiler_exit_scope(). Note that we don't track recursion levels during compilation - the task of detecting and rejecting excessive levels of nesting is handled by the symbol analysis pass. */ struct compiler { PyObject *c_filename; struct symtable *c_st; PyFutureFeatures *c_future; /* pointer to module's __future__ */ PyCompilerFlags *c_flags; int c_optimize; /* optimization level */ int c_interactive; /* true if in interactive mode */ int c_nestlevel; struct compiler_unit *u; /* compiler state for current block */ PyObject *c_stack; /* Python list holding compiler_unit ptrs */ PyArena *c_arena; /* pointer to memory allocation arena */ }; static int compiler_enter_scope(struct compiler *, identifier, int, void *, int); static void compiler_free(struct compiler *); static basicblock *compiler_new_block(struct compiler *); static int compiler_next_instr(struct compiler *, basicblock *); static int compiler_addop(struct compiler *, int); static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *); static int compiler_addop_i(struct compiler *, int, Py_ssize_t); static int compiler_addop_j(struct compiler *, int, basicblock *, int); static int compiler_error(struct compiler *, const char *); static int compiler_nameop(struct compiler *, identifier, expr_context_ty); static PyCodeObject *compiler_mod(struct compiler *, mod_ty); static int compiler_visit_stmt(struct compiler *, stmt_ty); static int compiler_visit_keyword(struct compiler *, keyword_ty); static int compiler_visit_expr(struct compiler *, expr_ty); static int compiler_augassign(struct compiler *, stmt_ty); static int compiler_annassign(struct compiler *, stmt_ty); static int compiler_visit_slice(struct compiler *, slice_ty, expr_context_ty); static int compiler_push_fblock(struct compiler *, enum fblocktype, basicblock *); static void compiler_pop_fblock(struct compiler *, enum fblocktype, basicblock *); /* Returns true if there is a loop on the fblock stack. */ static int compiler_in_loop(struct compiler *); static int inplace_binop(struct compiler *, operator_ty); static int expr_constant(struct compiler *, expr_ty); static int compiler_with(struct compiler *, stmt_ty, int); static int compiler_async_with(struct compiler *, stmt_ty, int); static int compiler_async_for(struct compiler *, stmt_ty); static int compiler_call_helper(struct compiler *c, int n, asdl_seq *args, asdl_seq *keywords); static int compiler_try_except(struct compiler *, stmt_ty); static int compiler_set_qualname(struct compiler *); static int compiler_sync_comprehension_generator( struct compiler *c, asdl_seq *generators, int gen_index, expr_ty elt, expr_ty val, int type); static int compiler_async_comprehension_generator( struct compiler *c, asdl_seq *generators, int gen_index, expr_ty elt, expr_ty val, int type); static PyCodeObject *assemble(struct compiler *, int addNone); static PyObject *__doc__; #define CAPSULE_NAME "compile.c compiler unit" PyObject * _Py_Mangle(PyObject *privateobj, PyObject *ident) { /* Name mangling: __private becomes _classname__private. This is independent from how the name is used. */ PyObject *result; size_t nlen, plen, ipriv; Py_UCS4 maxchar; if (privateobj == NULL || !PyUnicode_Check(privateobj) || PyUnicode_READ_CHAR(ident, 0) != '_' || PyUnicode_READ_CHAR(ident, 1) != '_') { Py_INCREF(ident); return ident; } nlen = PyUnicode_GET_LENGTH(ident); plen = PyUnicode_GET_LENGTH(privateobj); /* Don't mangle __id__ or names with dots. The only time a name with a dot can occur is when we are compiling an import statement that has a package name. TODO(jhylton): Decide whether we want to support mangling of the module name, e.g. __M.X. */ if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' && PyUnicode_READ_CHAR(ident, nlen-2) == '_') || PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) { Py_INCREF(ident); return ident; /* Don't mangle __whatever__ */ } /* Strip leading underscores from class name */ ipriv = 0; while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_') ipriv++; if (ipriv == plen) { Py_INCREF(ident); return ident; /* Don't mangle if class is just underscores */ } plen -= ipriv; if (plen + nlen >= PY_SSIZE_T_MAX - 1) { PyErr_SetString(PyExc_OverflowError, "private identifier too large to be mangled"); return NULL; } maxchar = PyUnicode_MAX_CHAR_VALUE(ident); if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar) maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj); result = PyUnicode_New(1 + nlen + plen, maxchar); if (!result) return 0; /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */ PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_'); if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) { Py_DECREF(result); return NULL; } if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) { Py_DECREF(result); return NULL; } assert(_PyUnicode_CheckConsistency(result, 1)); return result; } static int compiler_init(struct compiler *c) { bzero(c, sizeof(struct compiler)); c->c_stack = PyList_New(0); if (!c->c_stack) return 0; return 1; } PyCodeObject * PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags, int optimize, PyArena *arena) { struct compiler c; PyCodeObject *co = NULL; PyCompilerFlags local_flags; int merged; if (!__doc__) { __doc__ = PyUnicode_InternFromString("__doc__"); if (!__doc__) return NULL; } if (!compiler_init(&c)) return NULL; Py_INCREF(filename); c.c_filename = filename; c.c_arena = arena; c.c_future = PyFuture_FromASTObject(mod, filename); if (c.c_future == NULL) goto finally; if (!flags) { local_flags.cf_flags = 0; flags = &local_flags; } merged = c.c_future->ff_features | flags->cf_flags; c.c_future->ff_features = merged; flags->cf_flags = merged; c.c_flags = flags; c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize; c.c_nestlevel = 0; c.c_st = PySymtable_BuildObject(mod, filename, c.c_future); if (c.c_st == NULL) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_SystemError, "no symtable"); goto finally; } co = compiler_mod(&c, mod); finally: compiler_free(&c); assert(co || PyErr_Occurred()); return co; } PyCodeObject * PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags, int optimize, PyArena *arena) { PyObject *filename; PyCodeObject *co; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) return NULL; co = PyAST_CompileObject(mod, filename, flags, optimize, arena); Py_DECREF(filename); return co; } PyCodeObject * PyNode_Compile(struct _node *n, const char *filename) { PyCodeObject *co = NULL; mod_ty mod; PyArena *arena = PyArena_New(); if (!arena) return NULL; mod = PyAST_FromNode(n, NULL, filename, arena); if (mod) co = PyAST_Compile(mod, filename, NULL, arena); PyArena_Free(arena); return co; } static void compiler_free(struct compiler *c) { if (c->c_st) PySymtable_Free(c->c_st); if (c->c_future) PyObject_Free(c->c_future); Py_XDECREF(c->c_filename); Py_DECREF(c->c_stack); } static PyObject * list2dict(PyObject *list) { Py_ssize_t i, n; PyObject *v, *k; PyObject *dict = PyDict_New(); if (!dict) return NULL; n = PyList_Size(list); for (i = 0; i < n; i++) { v = PyLong_FromSsize_t(i); if (!v) { Py_DECREF(dict); return NULL; } k = PyList_GET_ITEM(list, i); k = _PyCode_ConstantKey(k); if (k == NULL || PyDict_SetItem(dict, k, v) < 0) { Py_XDECREF(k); Py_DECREF(v); Py_DECREF(dict); return NULL; } Py_DECREF(k); Py_DECREF(v); } return dict; } /* Return new dict containing names from src that match scope(s). src is a symbol table dictionary. If the scope of a name matches either scope_type or flag is set, insert it into the new dict. The values are integers, starting at offset and increasing by one for each key. */ static PyObject * dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset) { Py_ssize_t i = offset, scope, num_keys, key_i; PyObject *k, *v, *dest = PyDict_New(); PyObject *sorted_keys; assert(offset >= 0); if (dest == NULL) return NULL; /* Sort the keys so that we have a deterministic order on the indexes saved in the returned dictionary. These indexes are used as indexes into the free and cell var storage. Therefore if they aren't deterministic, then the generated bytecode is not deterministic. */ sorted_keys = PyDict_Keys(src); if (sorted_keys == NULL) return NULL; if (PyList_Sort(sorted_keys) != 0) { Py_DECREF(sorted_keys); return NULL; } num_keys = PyList_GET_SIZE(sorted_keys); for (key_i = 0; key_i < num_keys; key_i++) { /* XXX this should probably be a macro in symtable.h */ long vi; k = PyList_GET_ITEM(sorted_keys, key_i); v = PyDict_GetItem(src, k); assert(PyLong_Check(v)); vi = PyLong_AS_LONG(v); scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK; if (scope == scope_type || vi & flag) { PyObject *tuple, *item = PyLong_FromSsize_t(i); if (item == NULL) { Py_DECREF(sorted_keys); Py_DECREF(dest); return NULL; } i++; tuple = _PyCode_ConstantKey(k); if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) { Py_DECREF(sorted_keys); Py_DECREF(item); Py_DECREF(dest); Py_XDECREF(tuple); return NULL; } Py_DECREF(item); Py_DECREF(tuple); } } Py_DECREF(sorted_keys); return dest; } static void compiler_unit_check(struct compiler_unit *u) { basicblock *block; for (block = u->u_blocks; block != NULL; block = block->b_list) { assert((uintptr_t)block != 0xcbcbcbcbU); assert((uintptr_t)block != 0xfbfbfbfbU); assert((uintptr_t)block != 0xdbdbdbdbU); if (block->b_instr != NULL) { assert(block->b_ialloc > 0); assert(block->b_iused > 0); assert(block->b_ialloc >= block->b_iused); } else { assert (block->b_iused == 0); assert (block->b_ialloc == 0); } } } static void compiler_unit_free(struct compiler_unit *u) { basicblock *b, *next; compiler_unit_check(u); b = u->u_blocks; while (b != NULL) { if (b->b_instr) PyObject_Free((void *)b->b_instr); next = b->b_list; PyObject_Free((void *)b); b = next; } Py_CLEAR(u->u_ste); Py_CLEAR(u->u_name); Py_CLEAR(u->u_qualname); Py_CLEAR(u->u_consts); Py_CLEAR(u->u_names); Py_CLEAR(u->u_varnames); Py_CLEAR(u->u_freevars); Py_CLEAR(u->u_cellvars); Py_CLEAR(u->u_private); PyObject_Free(u); } static int compiler_enter_scope(struct compiler *c, identifier name, int scope_type, void *key, int lineno) { struct compiler_unit *u; basicblock *block; u = (struct compiler_unit *)PyObject_Malloc(sizeof( struct compiler_unit)); if (!u) { PyErr_NoMemory(); return 0; } bzero(u, sizeof(struct compiler_unit)); u->u_scope_type = scope_type; u->u_argcount = 0; u->u_kwonlyargcount = 0; u->u_ste = PySymtable_Lookup(c->c_st, key); if (!u->u_ste) { compiler_unit_free(u); return 0; } Py_INCREF(name); u->u_name = name; u->u_varnames = list2dict(u->u_ste->ste_varnames); u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0); if (!u->u_varnames || !u->u_cellvars) { compiler_unit_free(u); return 0; } if (u->u_ste->ste_needs_class_closure) { /* Cook up an implicit __class__ cell. */ _Py_IDENTIFIER(__class__); PyObject *tuple, *name, *zero; int res; assert(u->u_scope_type == COMPILER_SCOPE_CLASS); assert(PyDict_Size(u->u_cellvars) == 0); name = _PyUnicode_FromId(&PyId___class__); if (!name) { compiler_unit_free(u); return 0; } tuple = _PyCode_ConstantKey(name); if (!tuple) { compiler_unit_free(u); return 0; } zero = PyLong_FromLong(0); if (!zero) { Py_DECREF(tuple); compiler_unit_free(u); return 0; } res = PyDict_SetItem(u->u_cellvars, tuple, zero); Py_DECREF(tuple); Py_DECREF(zero); if (res < 0) { compiler_unit_free(u); return 0; } } u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS, PyDict_Size(u->u_cellvars)); if (!u->u_freevars) { compiler_unit_free(u); return 0; } u->u_blocks = NULL; u->u_nfblocks = 0; u->u_firstlineno = lineno; u->u_lineno = 0; u->u_col_offset = 0; u->u_lineno_set = 0; u->u_consts = PyDict_New(); if (!u->u_consts) { compiler_unit_free(u); return 0; } u->u_names = PyDict_New(); if (!u->u_names) { compiler_unit_free(u); return 0; } u->u_private = NULL; /* Push the old compiler_unit on the stack. */ if (c->u) { PyObject *capsule = PyCapsule_New(c->u, CAPSULE_NAME, NULL); if (!capsule || PyList_Append(c->c_stack, capsule) < 0) { Py_XDECREF(capsule); compiler_unit_free(u); return 0; } Py_DECREF(capsule); u->u_private = c->u->u_private; Py_XINCREF(u->u_private); } c->u = u; c->c_nestlevel++; block = compiler_new_block(c); if (block == NULL) return 0; c->u->u_curblock = block; if (u->u_scope_type != COMPILER_SCOPE_MODULE) { if (!compiler_set_qualname(c)) return 0; } return 1; } static void compiler_exit_scope(struct compiler *c) { Py_ssize_t n; PyObject *capsule; c->c_nestlevel--; compiler_unit_free(c->u); /* Restore c->u to the parent unit. */ n = PyList_GET_SIZE(c->c_stack) - 1; if (n >= 0) { capsule = PyList_GET_ITEM(c->c_stack, n); c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME); assert(c->u); /* we are deleting from a list so this really shouldn't fail */ if (PySequence_DelItem(c->c_stack, n) < 0) Py_FatalError("compiler_exit_scope()"); compiler_unit_check(c->u); } else c->u = NULL; } static int compiler_set_qualname(struct compiler *c) { _Py_static_string(dot, "."); _Py_static_string(dot_locals, ".<locals>"); Py_ssize_t stack_size; struct compiler_unit *u = c->u; PyObject *name, *base, *dot_str, *dot_locals_str; base = NULL; stack_size = PyList_GET_SIZE(c->c_stack); assert(stack_size >= 1); if (stack_size > 1) { int scope, force_global = 0; struct compiler_unit *parent; PyObject *mangled, *capsule; capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1); parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, CAPSULE_NAME); assert(parent); if (u->u_scope_type == COMPILER_SCOPE_FUNCTION || u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION || u->u_scope_type == COMPILER_SCOPE_CLASS) { assert(u->u_name); mangled = _Py_Mangle(parent->u_private, u->u_name); if (!mangled) return 0; scope = PyST_GetScope(parent->u_ste, mangled); Py_DECREF(mangled); assert(scope != GLOBAL_IMPLICIT); if (scope == GLOBAL_EXPLICIT) force_global = 1; } if (!force_global) { if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION || parent->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) { dot_locals_str = _PyUnicode_FromId(&dot_locals); if (dot_locals_str == NULL) return 0; base = PyUnicode_Concat(parent->u_qualname, dot_locals_str); if (base == NULL) return 0; } else { Py_INCREF(parent->u_qualname); base = parent->u_qualname; } } } if (base != NULL) { dot_str = _PyUnicode_FromId(&dot); if (dot_str == NULL) { Py_DECREF(base); return 0; } name = PyUnicode_Concat(base, dot_str); Py_DECREF(base); if (name == NULL) return 0; PyUnicode_Append(&name, u->u_name); if (name == NULL) return 0; } else { Py_INCREF(u->u_name); name = u->u_name; } u->u_qualname = name; return 1; } /* Allocate a new block and return a pointer to it. Returns NULL on error. */ static basicblock * compiler_new_block(struct compiler *c) { basicblock *b; struct compiler_unit *u; u = c->u; b = (basicblock *)PyObject_Malloc(sizeof(basicblock)); if (b == NULL) { PyErr_NoMemory(); return NULL; } bzero((void *)b, sizeof(basicblock)); /* Extend the singly linked list of blocks with new block. */ b->b_list = u->u_blocks; u->u_blocks = b; return b; } static basicblock * compiler_next_block(struct compiler *c) { basicblock *block = compiler_new_block(c); if (block == NULL) return NULL; c->u->u_curblock->b_next = block; c->u->u_curblock = block; return block; } static basicblock * compiler_use_next_block(struct compiler *c, basicblock *block) { assert(block != NULL); c->u->u_curblock->b_next = block; c->u->u_curblock = block; return block; } /* Returns the offset of the next instruction in the current block's b_instr array. Resizes the b_instr as necessary. Returns -1 on failure. */ static int compiler_next_instr(struct compiler *c, basicblock *b) { assert(b != NULL); if (b->b_instr == NULL) { b->b_instr = (struct instr *)PyObject_Malloc( sizeof(struct instr) * DEFAULT_BLOCK_SIZE); if (b->b_instr == NULL) { PyErr_NoMemory(); return -1; } b->b_ialloc = DEFAULT_BLOCK_SIZE; bzero((char *)b->b_instr, sizeof(struct instr) * DEFAULT_BLOCK_SIZE); } else if (b->b_iused == b->b_ialloc) { struct instr *tmp; size_t oldsize, newsize; oldsize = b->b_ialloc * sizeof(struct instr); newsize = oldsize << 1; if (oldsize > (SIZE_MAX >> 1)) { PyErr_NoMemory(); return -1; } if (newsize == 0) { PyErr_NoMemory(); return -1; } b->b_ialloc <<= 1; tmp = (struct instr *)PyObject_Realloc( (void *)b->b_instr, newsize); if (tmp == NULL) { PyErr_NoMemory(); return -1; } b->b_instr = tmp; bzero((char *)b->b_instr + oldsize, newsize - oldsize); } return b->b_iused++; } /* Set the i_lineno member of the instruction at offset off if the line number for the current expression/statement has not already been set. If it has been set, the call has no effect. The line number is reset in the following cases: - when entering a new scope - on each statement - on each expression that start a new line - before the "except" clause - before the "for" and "while" expressions */ static void compiler_set_lineno(struct compiler *c, int off) { basicblock *b; if (c->u->u_lineno_set) return; c->u->u_lineno_set = 1; b = c->u->u_curblock; b->b_instr[off].i_lineno = c->u->u_lineno; } int PyCompile_OpcodeStackEffect(int opcode, int oparg) { switch (opcode) { case POP_TOP: return -1; case ROT_TWO: case ROT_THREE: return 0; case DUP_TOP: return 1; case DUP_TOP_TWO: return 2; case UNARY_POSITIVE: case UNARY_NEGATIVE: case UNARY_NOT: case UNARY_INVERT: return 0; case SET_ADD: case LIST_APPEND: return -1; case MAP_ADD: return -2; case BINARY_POWER: case BINARY_MULTIPLY: case BINARY_MATRIX_MULTIPLY: case BINARY_MODULO: case BINARY_ADD: case BINARY_SUBTRACT: case BINARY_SUBSCR: case BINARY_FLOOR_DIVIDE: case BINARY_TRUE_DIVIDE: return -1; case INPLACE_FLOOR_DIVIDE: case INPLACE_TRUE_DIVIDE: return -1; case INPLACE_ADD: case INPLACE_SUBTRACT: case INPLACE_MULTIPLY: case INPLACE_MATRIX_MULTIPLY: case INPLACE_MODULO: return -1; case STORE_SUBSCR: return -3; case DELETE_SUBSCR: return -2; case BINARY_LSHIFT: case BINARY_RSHIFT: case BINARY_AND: case BINARY_XOR: case BINARY_OR: return -1; case INPLACE_POWER: return -1; case GET_ITER: return 0; case PRINT_EXPR: return -1; case LOAD_BUILD_CLASS: return 1; case INPLACE_LSHIFT: case INPLACE_RSHIFT: case INPLACE_AND: case INPLACE_XOR: case INPLACE_OR: return -1; case BREAK_LOOP: return 0; case SETUP_WITH: return 7; case WITH_CLEANUP_START: return 1; case WITH_CLEANUP_FINISH: return -1; /* XXX Sometimes more */ case RETURN_VALUE: return -1; case IMPORT_STAR: return -1; case SETUP_ANNOTATIONS: return 0; case YIELD_VALUE: return 0; case YIELD_FROM: return -1; case POP_BLOCK: return 0; case POP_EXCEPT: return 0; /* -3 except if bad bytecode */ case END_FINALLY: return -1; /* or -2 or -3 if exception occurred */ case STORE_NAME: return -1; case DELETE_NAME: return 0; case UNPACK_SEQUENCE: return oparg-1; case UNPACK_EX: return (oparg&0xFF) + (oparg>>8); case FOR_ITER: return 1; /* or -1, at end of iterator */ case STORE_ATTR: return -2; case DELETE_ATTR: return -1; case STORE_GLOBAL: return -1; case DELETE_GLOBAL: return 0; case LOAD_CONST: return 1; case LOAD_NAME: return 1; case BUILD_TUPLE: case BUILD_LIST: case BUILD_SET: case BUILD_STRING: return 1-oparg; case BUILD_LIST_UNPACK: case BUILD_TUPLE_UNPACK: case BUILD_TUPLE_UNPACK_WITH_CALL: case BUILD_SET_UNPACK: case BUILD_MAP_UNPACK: case BUILD_MAP_UNPACK_WITH_CALL: return 1 - oparg; case BUILD_MAP: return 1 - 2*oparg; case BUILD_CONST_KEY_MAP: return -oparg; case LOAD_ATTR: return 0; case COMPARE_OP: return -1; case IMPORT_NAME: return -1; case IMPORT_FROM: return 1; case JUMP_FORWARD: case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */ case JUMP_IF_FALSE_OR_POP: /* "" */ case JUMP_ABSOLUTE: return 0; case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: return -1; case LOAD_GLOBAL: return 1; case CONTINUE_LOOP: return 0; case SETUP_LOOP: return 0; case SETUP_EXCEPT: case SETUP_FINALLY: return 6; /* can push 3 values for the new exception + 3 others for the previous exception state */ case LOAD_FAST: return 1; case STORE_FAST: return -1; case DELETE_FAST: return 0; case STORE_ANNOTATION: return -1; case RAISE_VARARGS: return -oparg; case CALL_FUNCTION: return -oparg; case CALL_METHOD: return -oparg-1; case CALL_FUNCTION_KW: return -oparg-1; case CALL_FUNCTION_EX: return -1 - ((oparg & 0x01) != 0); case MAKE_FUNCTION: return -1 - ((oparg & 0x01) != 0) - ((oparg & 0x02) != 0) - ((oparg & 0x04) != 0) - ((oparg & 0x08) != 0); case BUILD_SLICE: if (oparg == 3) return -2; else return -1; case LOAD_CLOSURE: return 1; case LOAD_DEREF: case LOAD_CLASSDEREF: return 1; case STORE_DEREF: return -1; case DELETE_DEREF: return 0; case GET_AWAITABLE: return 0; case SETUP_ASYNC_WITH: return 6; case BEFORE_ASYNC_WITH: return 1; case GET_AITER: return 0; case GET_ANEXT: return 1; case GET_YIELD_FROM_ITER: return 0; case FORMAT_VALUE: /* If there's a fmt_spec on the stack, we go from 2->1, else 1->1. */ return (oparg & FVS_MASK) == FVS_HAVE_SPEC ? -1 : 0; case LOAD_METHOD: return 1; default: return PY_INVALID_STACK_EFFECT; } return PY_INVALID_STACK_EFFECT; /* not reachable */ } /* Add an opcode with no argument. Returns 0 on failure, 1 on success. */ static int compiler_addop(struct compiler *c, int opcode) { basicblock *b; struct instr *i; int off; assert(!HAS_ARG(opcode)); off = compiler_next_instr(c, c->u->u_curblock); if (off < 0) return 0; b = c->u->u_curblock; i = &b->b_instr[off]; i->i_opcode = opcode; i->i_oparg = 0; if (opcode == RETURN_VALUE) b->b_return = 1; compiler_set_lineno(c, off); return 1; } static Py_ssize_t compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o) { PyObject *t, *v; Py_ssize_t arg; t = _PyCode_ConstantKey(o); if (t == NULL) return -1; v = PyDict_GetItem(dict, t); if (!v) { if (PyErr_Occurred()) { Py_DECREF(t); return -1; } arg = PyDict_Size(dict); v = PyLong_FromSsize_t(arg); if (!v) { Py_DECREF(t); return -1; } if (PyDict_SetItem(dict, t, v) < 0) { Py_DECREF(t); Py_DECREF(v); return -1; } Py_DECREF(v); } else arg = PyLong_AsLong(v); Py_DECREF(t); return arg; } static int compiler_addop_o(struct compiler *c, int opcode, PyObject *dict, PyObject *o) { Py_ssize_t arg = compiler_add_o(c, dict, o); if (arg < 0) return 0; return compiler_addop_i(c, opcode, arg); } static int compiler_addop_name(struct compiler *c, int opcode, PyObject *dict, PyObject *o) { Py_ssize_t arg; PyObject *mangled = _Py_Mangle(c->u->u_private, o); if (!mangled) return 0; arg = compiler_add_o(c, dict, mangled); Py_DECREF(mangled); if (arg < 0) return 0; return compiler_addop_i(c, opcode, arg); } /* Add an opcode with an integer argument. Returns 0 on failure, 1 on success. */ static int compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg) { struct instr *i; int off; /* oparg value is unsigned, but a signed C int is usually used to store it in the C code (like Python/ceval.c). Limit to 32-bit signed C int (rather than INT_MAX) for portability. The argument of a concrete bytecode instruction is limited to 8-bit. EXTENDED_ARG is used for 16, 24, and 32-bit arguments. */ assert(HAS_ARG(opcode)); assert(0 <= oparg && oparg <= 2147483647); off = compiler_next_instr(c, c->u->u_curblock); if (off < 0) return 0; i = &c->u->u_curblock->b_instr[off]; i->i_opcode = opcode; i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int); compiler_set_lineno(c, off); return 1; } static int compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute) { struct instr *i; int off; assert(HAS_ARG(opcode)); assert(b != NULL); off = compiler_next_instr(c, c->u->u_curblock); if (off < 0) return 0; i = &c->u->u_curblock->b_instr[off]; i->i_opcode = opcode; i->i_target = b; if (absolute) i->i_jabs = 1; else i->i_jrel = 1; compiler_set_lineno(c, off); return 1; } /* NEXT_BLOCK() creates an implicit jump from the current block to the new block. The returns inside this macro make it impossible to decref objects created in the local function. Local objects should use the arena. */ #define NEXT_BLOCK(C) { \ if (compiler_next_block((C)) == NULL) \ return 0; \ } #define ADDOP(C, OP) { \ if (!compiler_addop((C), (OP))) \ return 0; \ } #define ADDOP_IN_SCOPE(C, OP) { \ if (!compiler_addop((C), (OP))) { \ compiler_exit_scope(c); \ return 0; \ } \ } #define ADDOP_O(C, OP, O, TYPE) { \ if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \ return 0; \ } /* Same as ADDOP_O, but steals a reference. */ #define ADDOP_N(C, OP, O, TYPE) { \ if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) { \ Py_DECREF((O)); \ return 0; \ } \ Py_DECREF((O)); \ } #define ADDOP_NAME(C, OP, O, TYPE) { \ if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \ return 0; \ } #define ADDOP_I(C, OP, O) { \ if (!compiler_addop_i((C), (OP), (O))) \ return 0; \ } #define ADDOP_JABS(C, OP, O) { \ if (!compiler_addop_j((C), (OP), (O), 1)) \ return 0; \ } #define ADDOP_JREL(C, OP, O) { \ if (!compiler_addop_j((C), (OP), (O), 0)) \ return 0; \ } /* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use the ASDL name to synthesize the name of the C type and the visit function. */ #define VISIT(C, TYPE, V) {\ if (!compiler_visit_ ## TYPE((C), (V))) \ return 0; \ } #define VISIT_IN_SCOPE(C, TYPE, V) {\ if (!compiler_visit_ ## TYPE((C), (V))) { \ compiler_exit_scope(c); \ return 0; \ } \ } #define VISIT_SLICE(C, V, CTX) {\ if (!compiler_visit_slice((C), (V), (CTX))) \ return 0; \ } #define VISIT_SEQ(C, TYPE, SEQ) { \ int _i; \ asdl_seq *seq = (SEQ); /* avoid variable capture */ \ for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ if (!compiler_visit_ ## TYPE((C), elt)) \ return 0; \ } \ } #define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \ int _i; \ asdl_seq *seq = (SEQ); /* avoid variable capture */ \ for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ if (!compiler_visit_ ## TYPE((C), elt)) { \ compiler_exit_scope(c); \ return 0; \ } \ } \ } static int compiler_isdocstring(stmt_ty s) { if (s->kind != Expr_kind) return 0; if (s->v.Expr.value->kind == Str_kind) return 1; if (s->v.Expr.value->kind == Constant_kind) return PyUnicode_CheckExact(s->v.Expr.value->v.Constant.value); return 0; } static int is_const(expr_ty e) { switch (e->kind) { case Constant_kind: case Num_kind: case Str_kind: case Bytes_kind: case Ellipsis_kind: case NameConstant_kind: return 1; case Name_kind: return _PyUnicode_EqualToASCIIString(e->v.Name.id, "__debug__"); default: return 0; } } static PyObject * get_const_value(struct compiler *c, expr_ty e) { switch (e->kind) { case Constant_kind: return e->v.Constant.value; case Num_kind: return e->v.Num.n; case Str_kind: return e->v.Str.s; case Bytes_kind: return e->v.Bytes.s; case Ellipsis_kind: return Py_Ellipsis; case NameConstant_kind: return e->v.NameConstant.value; case Name_kind: assert(_PyUnicode_EqualToASCIIString(e->v.Name.id, "__debug__")); return c->c_optimize ? Py_False : Py_True; default: assert(!is_const(e)); return NULL; } } /* Search if variable annotations are present statically in a block. */ static int find_ann(asdl_seq *stmts) { int i, j, res = 0; stmt_ty st; for (i = 0; i < asdl_seq_LEN(stmts); i++) { st = (stmt_ty)asdl_seq_GET(stmts, i); switch (st->kind) { case AnnAssign_kind: return 1; case For_kind: res = find_ann(st->v.For.body) || find_ann(st->v.For.orelse); break; case AsyncFor_kind: res = find_ann(st->v.AsyncFor.body) || find_ann(st->v.AsyncFor.orelse); break; case While_kind: res = find_ann(st->v.While.body) || find_ann(st->v.While.orelse); break; case If_kind: res = find_ann(st->v.If.body) || find_ann(st->v.If.orelse); break; case With_kind: res = find_ann(st->v.With.body); break; case AsyncWith_kind: res = find_ann(st->v.AsyncWith.body); break; case Try_kind: for (j = 0; j < asdl_seq_LEN(st->v.Try.handlers); j++) { excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET( st->v.Try.handlers, j); if (find_ann(handler->v.ExceptHandler.body)) { return 1; } } res = find_ann(st->v.Try.body) || find_ann(st->v.Try.finalbody) || find_ann(st->v.Try.orelse); break; default: res = 0; } if (res) { break; } } return res; } /* Compile a sequence of statements, checking for a docstring and for annotations. */ static int compiler_body(struct compiler *c, asdl_seq *stmts) { int i = 0; stmt_ty st; /* Set current line number to the line number of first statement. This way line number for SETUP_ANNOTATIONS will always coincide with the line number of first "real" statement in module. If body is empy, then lineno will be set later in assemble. */ if (c->u->u_scope_type == COMPILER_SCOPE_MODULE && !c->u->u_lineno && asdl_seq_LEN(stmts)) { st = (stmt_ty)asdl_seq_GET(stmts, 0); c->u->u_lineno = st->lineno; } /* Every annotated class and module should have __annotations__. */ if (find_ann(stmts)) { ADDOP(c, SETUP_ANNOTATIONS); } if (!asdl_seq_LEN(stmts)) return 1; st = (stmt_ty)asdl_seq_GET(stmts, 0); if (compiler_isdocstring(st) && c->c_optimize < 2) { /* don't generate docstrings if -OO */ i = 1; VISIT(c, expr, st->v.Expr.value); if (!compiler_nameop(c, __doc__, Store)) return 0; } for (; i < asdl_seq_LEN(stmts); i++) VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i)); return 1; } static PyCodeObject * compiler_mod(struct compiler *c, mod_ty mod) { PyCodeObject *co; int addNone = 1; static PyObject *module; if (!module) { module = PyUnicode_InternFromString("<module>"); if (!module) return NULL; } /* Use 0 for firstlineno initially, will fixup in assemble(). */ if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0)) return NULL; switch (mod->kind) { case Module_kind: if (!compiler_body(c, mod->v.Module.body)) { compiler_exit_scope(c); return 0; } break; case Interactive_kind: if (find_ann(mod->v.Interactive.body)) { ADDOP(c, SETUP_ANNOTATIONS); } c->c_interactive = 1; VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body); break; case Expression_kind: VISIT_IN_SCOPE(c, expr, mod->v.Expression.body); addNone = 0; break; case Suite_kind: PyErr_SetString(PyExc_SystemError, "suite should not be possible"); return 0; default: PyErr_Format(PyExc_SystemError, "module kind %d should not be possible", mod->kind); return 0; } co = assemble(c, addNone); compiler_exit_scope(c); return co; } /* The test for LOCAL must come before the test for FREE in order to handle classes where name is both local and free. The local var is a method and the free var is a free var referenced within a method. */ static int get_ref_type(struct compiler *c, PyObject *name) { int scope; if (c->u->u_scope_type == COMPILER_SCOPE_CLASS && _PyUnicode_EqualToASCIIString(name, "__class__")) return CELL; scope = PyST_GetScope(c->u->u_ste, name); if (scope == 0) { char buf[350]; PyOS_snprintf(buf, sizeof(buf), "unknown scope for %.100s in %.100s(%s)\n" "symbols: %s\nlocals: %s\nglobals: %s", PyUnicode_AsUTF8(name), PyUnicode_AsUTF8(c->u->u_name), PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_id)), PyUnicode_AsUTF8(PyObject_Repr(c->u->u_ste->ste_symbols)), PyUnicode_AsUTF8(PyObject_Repr(c->u->u_varnames)), PyUnicode_AsUTF8(PyObject_Repr(c->u->u_names)) ); Py_FatalError(buf); } return scope; } static int compiler_lookup_arg(PyObject *dict, PyObject *name) { PyObject *k, *v; k = _PyCode_ConstantKey(name); if (k == NULL) return -1; v = PyDict_GetItem(dict, k); Py_DECREF(k); if (v == NULL) return -1; return PyLong_AS_LONG(v); } static int compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t flags, PyObject *qualname) { Py_ssize_t i, free = PyCode_GetNumFree(co); if (qualname == NULL) qualname = co->co_name; if (free) { for (i = 0; i < free; ++i) { /* Bypass com_addop_varname because it will generate LOAD_DEREF but LOAD_CLOSURE is needed. */ PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); int arg, reftype; /* Special case: If a class contains a method with a free variable that has the same name as a method, the name will be considered free *and* local in the class. It should be handled by the closure, as well as by the normal name loookup logic. */ reftype = get_ref_type(c, name); if (reftype == CELL) arg = compiler_lookup_arg(c->u->u_cellvars, name); else /* (reftype == FREE) */ arg = compiler_lookup_arg(c->u->u_freevars, name); if (arg == -1) { fprintf(stderr, "lookup %s in %s %d %d\n" "freevars of %s: %s\n", PyUnicode_AsUTF8(PyObject_Repr(name)), PyUnicode_AsUTF8(c->u->u_name), reftype, arg, PyUnicode_AsUTF8(co->co_name), PyUnicode_AsUTF8(PyObject_Repr(co->co_freevars))); Py_FatalError("compiler_make_closure()"); } ADDOP_I(c, LOAD_CLOSURE, arg); } flags |= 0x08; ADDOP_I(c, BUILD_TUPLE, free); } ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); ADDOP_O(c, LOAD_CONST, qualname, consts); ADDOP_I(c, MAKE_FUNCTION, flags); return 1; } static int compiler_decorators(struct compiler *c, asdl_seq* decos) { int i; if (!decos) return 1; for (i = 0; i < asdl_seq_LEN(decos); i++) { VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i)); } return 1; } static int compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs, asdl_seq *kw_defaults) { /* Push a dict of keyword-only default values. Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed. */ int i; PyObject *keys = NULL; for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) { arg_ty arg = asdl_seq_GET(kwonlyargs, i); expr_ty default_ = asdl_seq_GET(kw_defaults, i); if (default_) { PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg); if (!mangled) { goto error; } if (keys == NULL) { keys = PyList_New(1); if (keys == NULL) { Py_DECREF(mangled); return 0; } PyList_SET_ITEM(keys, 0, mangled); } else { int res = PyList_Append(keys, mangled); Py_DECREF(mangled); if (res == -1) { goto error; } } if (!compiler_visit_expr(c, default_)) { goto error; } } } if (keys != NULL) { Py_ssize_t default_count = PyList_GET_SIZE(keys); PyObject *keys_tuple = PyList_AsTuple(keys); Py_DECREF(keys); if (keys_tuple == NULL) { return 0; } ADDOP_N(c, LOAD_CONST, keys_tuple, consts); ADDOP_I(c, BUILD_CONST_KEY_MAP, default_count); assert(default_count > 0); return 1; } else { return -1; } error: Py_XDECREF(keys); return 0; } static int compiler_visit_argannotation(struct compiler *c, identifier id, expr_ty annotation, PyObject *names) { if (annotation) { PyObject *mangled; VISIT(c, expr, annotation); mangled = _Py_Mangle(c->u->u_private, id); if (!mangled) return 0; if (PyList_Append(names, mangled) < 0) { Py_DECREF(mangled); return 0; } Py_DECREF(mangled); } return 1; } static int compiler_visit_argannotations(struct compiler *c, asdl_seq* args, PyObject *names) { int i; for (i = 0; i < asdl_seq_LEN(args); i++) { arg_ty arg = (arg_ty)asdl_seq_GET(args, i); if (!compiler_visit_argannotation( c, arg->arg, arg->annotation, names)) return 0; } return 1; } static int compiler_visit_annotations(struct compiler *c, arguments_ty args, expr_ty returns) { /* Push arg annotation dict. The expressions are evaluated out-of-order wrt the source code. Return 0 on error, -1 if no dict pushed, 1 if a dict is pushed. */ static identifier return_str; PyObject *names; Py_ssize_t len; names = PyList_New(0); if (!names) return 0; if (!compiler_visit_argannotations(c, args->args, names)) goto error; if (args->vararg && args->vararg->annotation && !compiler_visit_argannotation(c, args->vararg->arg, args->vararg->annotation, names)) goto error; if (!compiler_visit_argannotations(c, args->kwonlyargs, names)) goto error; if (args->kwarg && args->kwarg->annotation && !compiler_visit_argannotation(c, args->kwarg->arg, args->kwarg->annotation, names)) goto error; if (!return_str) { return_str = PyUnicode_InternFromString("return"); if (!return_str) goto error; } if (!compiler_visit_argannotation(c, return_str, returns, names)) { goto error; } len = PyList_GET_SIZE(names); if (len) { PyObject *keytuple = PyList_AsTuple(names); Py_DECREF(names); if (keytuple == NULL) { return 0; } ADDOP_N(c, LOAD_CONST, keytuple, consts); ADDOP_I(c, BUILD_CONST_KEY_MAP, len); return 1; } else { Py_DECREF(names); return -1; } error: Py_DECREF(names); return 0; } static int compiler_visit_defaults(struct compiler *c, arguments_ty args) { VISIT_SEQ(c, expr, args->defaults); ADDOP_I(c, BUILD_TUPLE, asdl_seq_LEN(args->defaults)); return 1; } static Py_ssize_t compiler_default_arguments(struct compiler *c, arguments_ty args) { Py_ssize_t funcflags = 0; if (args->defaults && asdl_seq_LEN(args->defaults) > 0) { if (!compiler_visit_defaults(c, args)) return -1; funcflags |= 0x01; } if (args->kwonlyargs) { int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, args->kw_defaults); if (res == 0) { return -1; } else if (res > 0) { funcflags |= 0x02; } } return funcflags; } static int compiler_function(struct compiler *c, stmt_ty s, int is_async) { PyCodeObject *co; PyObject *qualname, *first_const = Py_None; arguments_ty args; expr_ty returns; identifier name; asdl_seq* decos; asdl_seq *body; stmt_ty st; Py_ssize_t i, n, funcflags; int docstring; int annotations; int scope_type; if (is_async) { assert(s->kind == AsyncFunctionDef_kind); args = s->v.AsyncFunctionDef.args; returns = s->v.AsyncFunctionDef.returns; decos = s->v.AsyncFunctionDef.decorator_list; name = s->v.AsyncFunctionDef.name; body = s->v.AsyncFunctionDef.body; scope_type = COMPILER_SCOPE_ASYNC_FUNCTION; } else { assert(s->kind == FunctionDef_kind); args = s->v.FunctionDef.args; returns = s->v.FunctionDef.returns; decos = s->v.FunctionDef.decorator_list; name = s->v.FunctionDef.name; body = s->v.FunctionDef.body; scope_type = COMPILER_SCOPE_FUNCTION; } if (!compiler_decorators(c, decos)) return 0; funcflags = compiler_default_arguments(c, args); if (funcflags == -1) { return 0; } annotations = compiler_visit_annotations(c, args, returns); if (annotations == 0) { return 0; } else if (annotations > 0) { funcflags |= 0x04; } if (!compiler_enter_scope(c, name, scope_type, (void *)s, s->lineno)) { return 0; } st = (stmt_ty)asdl_seq_GET(body, 0); docstring = compiler_isdocstring(st); if (docstring && c->c_optimize < 2) { if (st->v.Expr.value->kind == Constant_kind) first_const = st->v.Expr.value->v.Constant.value; else first_const = st->v.Expr.value->v.Str.s; } if (compiler_add_o(c, c->u->u_consts, first_const) < 0) { compiler_exit_scope(c); return 0; } c->u->u_argcount = asdl_seq_LEN(args->args); c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); n = asdl_seq_LEN(body); /* if there was a docstring, we need to skip the first statement */ for (i = docstring; i < n; i++) { st = (stmt_ty)asdl_seq_GET(body, i); VISIT_IN_SCOPE(c, stmt, st); } co = assemble(c, 1); qualname = c->u->u_qualname; Py_INCREF(qualname); compiler_exit_scope(c); if (co == NULL) { Py_XDECREF(qualname); Py_XDECREF(co); return 0; } compiler_make_closure(c, co, funcflags, qualname); Py_DECREF(qualname); Py_DECREF(co); /* decorators */ for (i = 0; i < asdl_seq_LEN(decos); i++) { ADDOP_I(c, CALL_FUNCTION, 1); } return compiler_nameop(c, name, Store); } static int compiler_class(struct compiler *c, stmt_ty s) { PyCodeObject *co; PyObject *str; int i; asdl_seq* decos = s->v.ClassDef.decorator_list; if (!compiler_decorators(c, decos)) return 0; /* ultimately generate code for: <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>) where: <func> is a function/closure created from the class body; it has a single argument (__locals__) where the dict (or MutableSequence) representing the locals is passed <name> is the class name <bases> is the positional arguments and *varargs argument <keywords> is the keyword arguments and **kwds argument This borrows from compiler_call. */ /* 1. compile the class body into a code object */ if (!compiler_enter_scope(c, s->v.ClassDef.name, COMPILER_SCOPE_CLASS, (void *)s, s->lineno)) return 0; /* this block represents what we do in the new scope */ { /* use the class name for name mangling */ Py_INCREF(s->v.ClassDef.name); Py_XSETREF(c->u->u_private, s->v.ClassDef.name); /* load (global) __name__ ... */ str = PyUnicode_InternFromString("__name__"); if (!str || !compiler_nameop(c, str, Load)) { Py_XDECREF(str); compiler_exit_scope(c); return 0; } Py_DECREF(str); /* ... and store it as __module__ */ str = PyUnicode_InternFromString("__module__"); if (!str || !compiler_nameop(c, str, Store)) { Py_XDECREF(str); compiler_exit_scope(c); return 0; } Py_DECREF(str); assert(c->u->u_qualname); ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts); str = PyUnicode_InternFromString("__qualname__"); if (!str || !compiler_nameop(c, str, Store)) { Py_XDECREF(str); compiler_exit_scope(c); return 0; } Py_DECREF(str); /* compile the body proper */ if (!compiler_body(c, s->v.ClassDef.body)) { compiler_exit_scope(c); return 0; } /* Return __classcell__ if it is referenced, otherwise return None */ if (c->u->u_ste->ste_needs_class_closure) { /* Store __classcell__ into class namespace & return it */ str = PyUnicode_InternFromString("__class__"); if (str == NULL) { compiler_exit_scope(c); return 0; } i = compiler_lookup_arg(c->u->u_cellvars, str); Py_DECREF(str); if (i < 0) { compiler_exit_scope(c); return 0; } assert(i == 0); ADDOP_I(c, LOAD_CLOSURE, i); ADDOP(c, DUP_TOP); str = PyUnicode_InternFromString("__classcell__"); if (!str || !compiler_nameop(c, str, Store)) { Py_XDECREF(str); compiler_exit_scope(c); return 0; } Py_DECREF(str); } else { /* No methods referenced __class__, so just return None */ assert(PyDict_Size(c->u->u_cellvars) == 0); ADDOP_O(c, LOAD_CONST, Py_None, consts); } ADDOP_IN_SCOPE(c, RETURN_VALUE); /* create the code object */ co = assemble(c, 1); } /* leave the new scope */ compiler_exit_scope(c); if (co == NULL) return 0; /* 2. load the 'build_class' function */ ADDOP(c, LOAD_BUILD_CLASS); /* 3. load a function (or closure) made from the code object */ compiler_make_closure(c, co, 0, NULL); Py_DECREF(co); /* 4. load class name */ ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts); /* 5. generate the rest of the code for the call */ if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords)) return 0; /* 6. apply decorators */ for (i = 0; i < asdl_seq_LEN(decos); i++) { ADDOP_I(c, CALL_FUNCTION, 1); } /* 7. store into <name> */ if (!compiler_nameop(c, s->v.ClassDef.name, Store)) return 0; return 1; } static int compiler_ifexp(struct compiler *c, expr_ty e) { basicblock *end, *next; assert(e->kind == IfExp_kind); end = compiler_new_block(c); if (end == NULL) return 0; next = compiler_new_block(c); if (next == NULL) return 0; VISIT(c, expr, e->v.IfExp.test); ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); VISIT(c, expr, e->v.IfExp.body); ADDOP_JREL(c, JUMP_FORWARD, end); compiler_use_next_block(c, next); VISIT(c, expr, e->v.IfExp.orelse); compiler_use_next_block(c, end); return 1; } static int compiler_lambda(struct compiler *c, expr_ty e) { PyCodeObject *co; PyObject *qualname; static identifier name; Py_ssize_t funcflags; arguments_ty args = e->v.Lambda.args; assert(e->kind == Lambda_kind); if (!name) { name = PyUnicode_InternFromString("<lambda>"); if (!name) return 0; } funcflags = compiler_default_arguments(c, args); if (funcflags == -1) { return 0; } if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA, (void *)e, e->lineno)) return 0; /* Make None the first constant, so the lambda can't have a docstring. */ if (compiler_add_o(c, c->u->u_consts, Py_None) < 0) return 0; c->u->u_argcount = asdl_seq_LEN(args->args); c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); VISIT_IN_SCOPE(c, expr, e->v.Lambda.body); if (c->u->u_ste->ste_generator) { co = assemble(c, 0); } else { ADDOP_IN_SCOPE(c, RETURN_VALUE); co = assemble(c, 1); } qualname = c->u->u_qualname; Py_INCREF(qualname); compiler_exit_scope(c); if (co == NULL) return 0; compiler_make_closure(c, co, funcflags, qualname); Py_DECREF(qualname); Py_DECREF(co); return 1; } static int compiler_if(struct compiler *c, stmt_ty s) { basicblock *end, *next; int constant; assert(s->kind == If_kind); end = compiler_new_block(c); if (end == NULL) return 0; constant = expr_constant(c, s->v.If.test); /* constant = 0: "if 0" * constant = 1: "if 1", "if 2", ... * constant = -1: rest */ if (constant == 0) { if (s->v.If.orelse) VISIT_SEQ(c, stmt, s->v.If.orelse); } else if (constant == 1) { VISIT_SEQ(c, stmt, s->v.If.body); } else { if (asdl_seq_LEN(s->v.If.orelse)) { next = compiler_new_block(c); if (next == NULL) return 0; } else next = end; VISIT(c, expr, s->v.If.test); ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); VISIT_SEQ(c, stmt, s->v.If.body); if (asdl_seq_LEN(s->v.If.orelse)) { ADDOP_JREL(c, JUMP_FORWARD, end); compiler_use_next_block(c, next); VISIT_SEQ(c, stmt, s->v.If.orelse); } } compiler_use_next_block(c, end); return 1; } static int compiler_for(struct compiler *c, stmt_ty s) { basicblock *start, *cleanup, *end; start = compiler_new_block(c); cleanup = compiler_new_block(c); end = compiler_new_block(c); if (start == NULL || end == NULL || cleanup == NULL) return 0; ADDOP_JREL(c, SETUP_LOOP, end); if (!compiler_push_fblock(c, LOOP, start)) return 0; VISIT(c, expr, s->v.For.iter); ADDOP(c, GET_ITER); compiler_use_next_block(c, start); ADDOP_JREL(c, FOR_ITER, cleanup); VISIT(c, expr, s->v.For.target); VISIT_SEQ(c, stmt, s->v.For.body); ADDOP_JABS(c, JUMP_ABSOLUTE, start); compiler_use_next_block(c, cleanup); ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, LOOP, start); VISIT_SEQ(c, stmt, s->v.For.orelse); compiler_use_next_block(c, end); return 1; } static int compiler_async_for(struct compiler *c, stmt_ty s) { _Py_IDENTIFIER(StopAsyncIteration); basicblock *try, *except, *end, *after_try, *try_cleanup, *after_loop_else; PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration); if (stop_aiter_error == NULL) { return 0; } try = compiler_new_block(c); except = compiler_new_block(c); end = compiler_new_block(c); after_try = compiler_new_block(c); try_cleanup = compiler_new_block(c); after_loop_else = compiler_new_block(c); if (try == NULL || except == NULL || end == NULL || after_try == NULL || try_cleanup == NULL || after_loop_else == NULL) return 0; ADDOP_JREL(c, SETUP_LOOP, end); if (!compiler_push_fblock(c, LOOP, try)) return 0; VISIT(c, expr, s->v.AsyncFor.iter); ADDOP(c, GET_AITER); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, YIELD_FROM); compiler_use_next_block(c, try); ADDOP_JREL(c, SETUP_EXCEPT, except); if (!compiler_push_fblock(c, EXCEPT, try)) return 0; ADDOP(c, GET_ANEXT); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, YIELD_FROM); VISIT(c, expr, s->v.AsyncFor.target); ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, EXCEPT, try); ADDOP_JREL(c, JUMP_FORWARD, after_try); compiler_use_next_block(c, except); ADDOP(c, DUP_TOP); ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names); ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH); ADDOP_JABS(c, POP_JUMP_IF_TRUE, try_cleanup); ADDOP(c, END_FINALLY); compiler_use_next_block(c, after_try); VISIT_SEQ(c, stmt, s->v.AsyncFor.body); ADDOP_JABS(c, JUMP_ABSOLUTE, try); compiler_use_next_block(c, try_cleanup); ADDOP(c, POP_TOP); ADDOP(c, POP_TOP); ADDOP(c, POP_TOP); ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */ ADDOP(c, POP_TOP); /* for correct calculation of stack effect */ ADDOP(c, POP_BLOCK); /* for SETUP_LOOP */ compiler_pop_fblock(c, LOOP, try); compiler_use_next_block(c, after_loop_else); VISIT_SEQ(c, stmt, s->v.For.orelse); compiler_use_next_block(c, end); return 1; } static int compiler_while(struct compiler *c, stmt_ty s) { basicblock *loop, *orelse, *end, *anchor = NULL; int constant = expr_constant(c, s->v.While.test); if (constant == 0) { if (s->v.While.orelse) VISIT_SEQ(c, stmt, s->v.While.orelse); return 1; } loop = compiler_new_block(c); end = compiler_new_block(c); if (constant == -1) { anchor = compiler_new_block(c); if (anchor == NULL) return 0; } if (loop == NULL || end == NULL) return 0; if (s->v.While.orelse) { orelse = compiler_new_block(c); if (orelse == NULL) return 0; } else orelse = NULL; ADDOP_JREL(c, SETUP_LOOP, end); compiler_use_next_block(c, loop); if (!compiler_push_fblock(c, LOOP, loop)) return 0; if (constant == -1) { VISIT(c, expr, s->v.While.test); ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor); } VISIT_SEQ(c, stmt, s->v.While.body); ADDOP_JABS(c, JUMP_ABSOLUTE, loop); /* XXX should the two POP instructions be in a separate block if there is no else clause ? */ if (constant == -1) compiler_use_next_block(c, anchor); ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, LOOP, loop); if (orelse != NULL) /* what if orelse is just pass? */ VISIT_SEQ(c, stmt, s->v.While.orelse); compiler_use_next_block(c, end); return 1; } static int compiler_continue(struct compiler *c) { static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop"; static const char IN_FINALLY_ERROR_MSG[] = "'continue' not supported inside 'finally' clause"; int i; if (!c->u->u_nfblocks) return compiler_error(c, LOOP_ERROR_MSG); i = c->u->u_nfblocks - 1; switch (c->u->u_fblock[i].fb_type) { case LOOP: ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block); break; case EXCEPT: case FINALLY_TRY: while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) { /* Prevent continue anywhere under a finally even if hidden in a sub-try or except. */ if (c->u->u_fblock[i].fb_type == FINALLY_END) return compiler_error(c, IN_FINALLY_ERROR_MSG); } if (i == -1) return compiler_error(c, LOOP_ERROR_MSG); ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block); break; case FINALLY_END: return compiler_error(c, IN_FINALLY_ERROR_MSG); } return 1; } /* Code generated for "try: <body> finally: <finalbody>" is as follows: SETUP_FINALLY L <code for body> POP_BLOCK LOAD_CONST <None> L: <code for finalbody> END_FINALLY The special instructions use the block stack. Each block stack entry contains the instruction that created it (here SETUP_FINALLY), the level of the value stack at the time the block stack entry was created, and a label (here L). SETUP_FINALLY: Pushes the current value stack level and the label onto the block stack. POP_BLOCK: Pops en entry from the block stack, and pops the value stack until its level is the same as indicated on the block stack. (The label is ignored.) END_FINALLY: Pops a variable number of entries from the *value* stack and re-raises the exception they specify. The number of entries popped depends on the (pseudo) exception type. The block stack is unwound when an exception is raised: when a SETUP_FINALLY entry is found, the exception is pushed onto the value stack (and the exception condition is cleared), and the interpreter jumps to the label gotten from the block stack. */ static int compiler_try_finally(struct compiler *c, stmt_ty s) { basicblock *body, *end; body = compiler_new_block(c); end = compiler_new_block(c); if (body == NULL || end == NULL) return 0; ADDOP_JREL(c, SETUP_FINALLY, end); compiler_use_next_block(c, body); if (!compiler_push_fblock(c, FINALLY_TRY, body)) return 0; if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) { if (!compiler_try_except(c, s)) return 0; } else { VISIT_SEQ(c, stmt, s->v.Try.body); } ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, FINALLY_TRY, body); ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_use_next_block(c, end); if (!compiler_push_fblock(c, FINALLY_END, end)) return 0; VISIT_SEQ(c, stmt, s->v.Try.finalbody); ADDOP(c, END_FINALLY); compiler_pop_fblock(c, FINALLY_END, end); return 1; } /* Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...": (The contents of the value stack is shown in [], with the top at the right; 'tb' is trace-back info, 'val' the exception's associated value, and 'exc' the exception.) Value stack Label Instruction Argument [] SETUP_EXCEPT L1 [] <code for S> [] POP_BLOCK [] JUMP_FORWARD L0 [tb, val, exc] L1: DUP ) [tb, val, exc, exc] <evaluate E1> ) [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 ) [tb, val, exc] POP [tb, val] <assign to V1> (or POP if no V1) [tb] POP [] <code for S1> JUMP_FORWARD L0 [tb, val, exc] L2: DUP .............................etc....................... [tb, val, exc] Ln+1: END_FINALLY # re-raise exception [] L0: <next statement> Of course, parts are not generated if Vi or Ei is not present. */ static int compiler_try_except(struct compiler *c, stmt_ty s) { basicblock *body, *orelse, *except, *end; Py_ssize_t i, n; body = compiler_new_block(c); except = compiler_new_block(c); orelse = compiler_new_block(c); end = compiler_new_block(c); if (body == NULL || except == NULL || orelse == NULL || end == NULL) return 0; ADDOP_JREL(c, SETUP_EXCEPT, except); compiler_use_next_block(c, body); if (!compiler_push_fblock(c, EXCEPT, body)) return 0; VISIT_SEQ(c, stmt, s->v.Try.body); ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, EXCEPT, body); ADDOP_JREL(c, JUMP_FORWARD, orelse); n = asdl_seq_LEN(s->v.Try.handlers); compiler_use_next_block(c, except); for (i = 0; i < n; i++) { excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET( s->v.Try.handlers, i); if (!handler->v.ExceptHandler.type && i < n-1) return compiler_error(c, "default 'except:' must be last"); c->u->u_lineno_set = 0; c->u->u_lineno = handler->lineno; c->u->u_col_offset = handler->col_offset; except = compiler_new_block(c); if (except == NULL) return 0; if (handler->v.ExceptHandler.type) { ADDOP(c, DUP_TOP); VISIT(c, expr, handler->v.ExceptHandler.type); ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH); ADDOP_JABS(c, POP_JUMP_IF_FALSE, except); } ADDOP(c, POP_TOP); if (handler->v.ExceptHandler.name) { basicblock *cleanup_end, *cleanup_body; cleanup_end = compiler_new_block(c); cleanup_body = compiler_new_block(c); if (cleanup_end == NULL || cleanup_body == NULL) { return 0; } compiler_nameop(c, handler->v.ExceptHandler.name, Store); ADDOP(c, POP_TOP); /* try: # body except type as name: try: # body finally: name = None del name */ /* second try: */ ADDOP_JREL(c, SETUP_FINALLY, cleanup_end); compiler_use_next_block(c, cleanup_body); if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) return 0; /* second # body */ VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); ADDOP(c, POP_BLOCK); ADDOP(c, POP_EXCEPT); compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); /* finally: */ ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_use_next_block(c, cleanup_end); if (!compiler_push_fblock(c, FINALLY_END, cleanup_end)) return 0; /* name = None */ ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_nameop(c, handler->v.ExceptHandler.name, Store); /* del name */ compiler_nameop(c, handler->v.ExceptHandler.name, Del); ADDOP(c, END_FINALLY); compiler_pop_fblock(c, FINALLY_END, cleanup_end); } else { basicblock *cleanup_body; cleanup_body = compiler_new_block(c); if (!cleanup_body) return 0; ADDOP(c, POP_TOP); ADDOP(c, POP_TOP); compiler_use_next_block(c, cleanup_body); if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) return 0; VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); ADDOP(c, POP_EXCEPT); compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); } ADDOP_JREL(c, JUMP_FORWARD, end); compiler_use_next_block(c, except); } ADDOP(c, END_FINALLY); compiler_use_next_block(c, orelse); VISIT_SEQ(c, stmt, s->v.Try.orelse); compiler_use_next_block(c, end); return 1; } static int compiler_try(struct compiler *c, stmt_ty s) { if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody)) return compiler_try_finally(c, s); else return compiler_try_except(c, s); } static int compiler_import_as(struct compiler *c, identifier name, identifier asname) { /* The IMPORT_NAME opcode was already generated. This function merely needs to bind the result to a name. If there is a dot in name, we need to split it and emit a LOAD_ATTR for each name. */ Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, PyUnicode_GET_LENGTH(name), 1); if (dot == -2) return 0; if (dot != -1) { /* Consume the base module name to get the first attribute */ Py_ssize_t pos = dot + 1; while (dot != -1) { PyObject *attr; dot = PyUnicode_FindChar(name, '.', pos, PyUnicode_GET_LENGTH(name), 1); if (dot == -2) return 0; attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : PyUnicode_GET_LENGTH(name)); if (!attr) return 0; ADDOP_N(c, LOAD_ATTR, attr, names); pos = dot + 1; } } return compiler_nameop(c, asname, Store); } static int compiler_import(struct compiler *c, stmt_ty s) { /* The Import node stores a module name like a.b.c as a single string. This is convenient for all cases except import a.b.c as d where we need to parse that string to extract the individual module names. XXX Perhaps change the representation to make this case simpler? */ Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names); for (i = 0; i < n; i++) { alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i); int r; PyObject *level; level = PyLong_FromLong(0); if (level == NULL) return 0; ADDOP_N(c, LOAD_CONST, level, consts); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP_NAME(c, IMPORT_NAME, alias->name, names); if (alias->asname) { r = compiler_import_as(c, alias->name, alias->asname); if (!r) return r; } else { identifier tmp = alias->name; Py_ssize_t dot = PyUnicode_FindChar( alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1); if (dot != -1) { tmp = PyUnicode_Substring(alias->name, 0, dot); if (tmp == NULL) return 0; } r = compiler_nameop(c, tmp, Store); if (dot != -1) { Py_DECREF(tmp); } if (!r) return r; } } return 1; } static int compiler_from_import(struct compiler *c, stmt_ty s) { Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names); PyObject *level, *names; static PyObject *empty_string; if (!empty_string) { empty_string = PyUnicode_FromString(""); if (!empty_string) return 0; } level = PyLong_FromLong(s->v.ImportFrom.level); if (!level) { return 0; } ADDOP_N(c, LOAD_CONST, level, consts); names = PyTuple_New(n); if (!names) return 0; /* build up the names */ for (i = 0; i < n; i++) { alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); Py_INCREF(alias->name); PyTuple_SET_ITEM(names, i, alias->name); } if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module && _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) { Py_DECREF(names); return compiler_error(c, "from __future__ imports must occur " "at the beginning of the file"); } ADDOP_N(c, LOAD_CONST, names, consts); if (s->v.ImportFrom.module) { ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names); } else { ADDOP_NAME(c, IMPORT_NAME, empty_string, names); } for (i = 0; i < n; i++) { alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); identifier store_name; if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') { assert(n == 1); ADDOP(c, IMPORT_STAR); return 1; } ADDOP_NAME(c, IMPORT_FROM, alias->name, names); store_name = alias->name; if (alias->asname) store_name = alias->asname; if (!compiler_nameop(c, store_name, Store)) { return 0; } } /* remove imported module */ ADDOP(c, POP_TOP); return 1; } static int compiler_assert(struct compiler *c, stmt_ty s) { static PyObject *assertion_error = NULL; basicblock *end; PyObject* msg; if (c->c_optimize) return 1; if (assertion_error == NULL) { assertion_error = PyUnicode_InternFromString("AssertionError"); if (assertion_error == NULL) return 0; } if (s->v.Assert.test->kind == Tuple_kind && asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) { msg = PyUnicode_FromString("assertion is always true, " "perhaps remove parentheses?"); if (msg == NULL) return 0; if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename, c->u->u_lineno, NULL, NULL) == -1) { Py_DECREF(msg); return 0; } Py_DECREF(msg); } VISIT(c, expr, s->v.Assert.test); end = compiler_new_block(c); if (end == NULL) return 0; ADDOP_JABS(c, POP_JUMP_IF_TRUE, end); ADDOP_O(c, LOAD_GLOBAL, assertion_error, names); if (s->v.Assert.msg) { VISIT(c, expr, s->v.Assert.msg); ADDOP_I(c, CALL_FUNCTION, 1); } ADDOP_I(c, RAISE_VARARGS, 1); compiler_use_next_block(c, end); return 1; } static int compiler_visit_stmt_expr(struct compiler *c, expr_ty value) { if (c->c_interactive && c->c_nestlevel <= 1) { VISIT(c, expr, value); ADDOP(c, PRINT_EXPR); return 1; } if (is_const(value)) { /* ignore constant statement */ return 1; } VISIT(c, expr, value); ADDOP(c, POP_TOP); return 1; } static int compiler_visit_stmt(struct compiler *c, stmt_ty s) { Py_ssize_t i, n; /* Always assign a lineno to the next instruction for a stmt. */ c->u->u_lineno = s->lineno; c->u->u_col_offset = s->col_offset; c->u->u_lineno_set = 0; switch (s->kind) { case FunctionDef_kind: return compiler_function(c, s, 0); case ClassDef_kind: return compiler_class(c, s); case Return_kind: if (c->u->u_ste->ste_type != FunctionBlock) return compiler_error(c, "'return' outside function"); if (s->v.Return.value) { if (c->u->u_ste->ste_coroutine && c->u->u_ste->ste_generator) return compiler_error( c, "'return' with value in async generator"); VISIT(c, expr, s->v.Return.value); } else ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, RETURN_VALUE); break; case Delete_kind: VISIT_SEQ(c, expr, s->v.Delete.targets) break; case Assign_kind: n = asdl_seq_LEN(s->v.Assign.targets); VISIT(c, expr, s->v.Assign.value); for (i = 0; i < n; i++) { if (i < n - 1) ADDOP(c, DUP_TOP); VISIT(c, expr, (expr_ty)asdl_seq_GET(s->v.Assign.targets, i)); } break; case AugAssign_kind: return compiler_augassign(c, s); case AnnAssign_kind: return compiler_annassign(c, s); case For_kind: return compiler_for(c, s); case While_kind: return compiler_while(c, s); case If_kind: return compiler_if(c, s); case Raise_kind: n = 0; if (s->v.Raise.exc) { VISIT(c, expr, s->v.Raise.exc); n++; if (s->v.Raise.cause) { VISIT(c, expr, s->v.Raise.cause); n++; } } ADDOP_I(c, RAISE_VARARGS, (int)n); break; case Try_kind: return compiler_try(c, s); case Assert_kind: return compiler_assert(c, s); case Import_kind: return compiler_import(c, s); case ImportFrom_kind: return compiler_from_import(c, s); case Global_kind: case Nonlocal_kind: break; case Expr_kind: return compiler_visit_stmt_expr(c, s->v.Expr.value); case Pass_kind: break; case Break_kind: if (!compiler_in_loop(c)) return compiler_error(c, "'break' outside loop"); ADDOP(c, BREAK_LOOP); break; case Continue_kind: return compiler_continue(c); case With_kind: return compiler_with(c, s, 0); case AsyncFunctionDef_kind: return compiler_function(c, s, 1); case AsyncWith_kind: return compiler_async_with(c, s, 0); case AsyncFor_kind: return compiler_async_for(c, s); } return 1; } static int unaryop(unaryop_ty op) { switch (op) { case Invert: return UNARY_INVERT; case Not: return UNARY_NOT; case UAdd: return UNARY_POSITIVE; case USub: return UNARY_NEGATIVE; default: PyErr_Format(PyExc_SystemError, "unary op %d should not be possible", op); return 0; } } static int binop(struct compiler *c, operator_ty op) { switch (op) { case Add: return BINARY_ADD; case Sub: return BINARY_SUBTRACT; case Mult: return BINARY_MULTIPLY; case MatMult: return BINARY_MATRIX_MULTIPLY; case Div: return BINARY_TRUE_DIVIDE; case Mod: return BINARY_MODULO; case Pow: return BINARY_POWER; case LShift: return BINARY_LSHIFT; case RShift: return BINARY_RSHIFT; case BitOr: return BINARY_OR; case BitXor: return BINARY_XOR; case BitAnd: return BINARY_AND; case FloorDiv: return BINARY_FLOOR_DIVIDE; default: PyErr_Format(PyExc_SystemError, "binary op %d should not be possible", op); return 0; } } static int cmpop(cmpop_ty op) { switch (op) { case Eq: return PyCmp_EQ; case NotEq: return PyCmp_NE; case Lt: return PyCmp_LT; case LtE: return PyCmp_LE; case Gt: return PyCmp_GT; case GtE: return PyCmp_GE; case Is: return PyCmp_IS; case IsNot: return PyCmp_IS_NOT; case In: return PyCmp_IN; case NotIn: return PyCmp_NOT_IN; default: return PyCmp_BAD; } } static int inplace_binop(struct compiler *c, operator_ty op) { switch (op) { case Add: return INPLACE_ADD; case Sub: return INPLACE_SUBTRACT; case Mult: return INPLACE_MULTIPLY; case MatMult: return INPLACE_MATRIX_MULTIPLY; case Div: return INPLACE_TRUE_DIVIDE; case Mod: return INPLACE_MODULO; case Pow: return INPLACE_POWER; case LShift: return INPLACE_LSHIFT; case RShift: return INPLACE_RSHIFT; case BitOr: return INPLACE_OR; case BitXor: return INPLACE_XOR; case BitAnd: return INPLACE_AND; case FloorDiv: return INPLACE_FLOOR_DIVIDE; default: PyErr_Format(PyExc_SystemError, "inplace binary op %d should not be possible", op); return 0; } } static int compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx) { int op, scope; Py_ssize_t arg; enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype; PyObject *dict = c->u->u_names; PyObject *mangled; /* XXX AugStore isn't used anywhere! */ assert(!_PyUnicode_EqualToASCIIString(name, "None") && !_PyUnicode_EqualToASCIIString(name, "True") && !_PyUnicode_EqualToASCIIString(name, "False")); if (ctx == Load && _PyUnicode_EqualToASCIIString(name, "__debug__")) { ADDOP_O(c, LOAD_CONST, c->c_optimize ? Py_False : Py_True, consts); return 1; } mangled = _Py_Mangle(c->u->u_private, name); if (!mangled) return 0; op = 0; optype = OP_NAME; scope = PyST_GetScope(c->u->u_ste, mangled); switch (scope) { case FREE: dict = c->u->u_freevars; optype = OP_DEREF; break; case CELL: dict = c->u->u_cellvars; optype = OP_DEREF; break; case LOCAL: if (c->u->u_ste->ste_type == FunctionBlock) optype = OP_FAST; break; case GLOBAL_IMPLICIT: if (c->u->u_ste->ste_type == FunctionBlock) optype = OP_GLOBAL; break; case GLOBAL_EXPLICIT: optype = OP_GLOBAL; break; default: /* scope can be 0 */ break; } /* XXX Leave assert here, but handle __doc__ and the like better */ assert(scope || PyUnicode_READ_CHAR(name, 0) == '_'); switch (optype) { case OP_DEREF: switch (ctx) { case Load: op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF; break; case Store: op = STORE_DEREF; break; case AugLoad: case AugStore: break; case Del: op = DELETE_DEREF; break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid for deref variable"); return 0; } break; case OP_FAST: switch (ctx) { case Load: op = LOAD_FAST; break; case Store: op = STORE_FAST; break; case Del: op = DELETE_FAST; break; case AugLoad: case AugStore: break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid for local variable"); return 0; } ADDOP_N(c, op, mangled, varnames); return 1; case OP_GLOBAL: switch (ctx) { case Load: op = LOAD_GLOBAL; break; case Store: op = STORE_GLOBAL; break; case Del: op = DELETE_GLOBAL; break; case AugLoad: case AugStore: break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid for global variable"); return 0; } break; case OP_NAME: switch (ctx) { case Load: op = LOAD_NAME; break; case Store: op = STORE_NAME; break; case Del: op = DELETE_NAME; break; case AugLoad: case AugStore: break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid for name variable"); return 0; } break; } assert(op); arg = compiler_add_o(c, dict, mangled); Py_DECREF(mangled); if (arg < 0) return 0; return compiler_addop_i(c, op, arg); } static int compiler_boolop(struct compiler *c, expr_ty e) { basicblock *end; int jumpi; Py_ssize_t i, n; asdl_seq *s; assert(e->kind == BoolOp_kind); if (e->v.BoolOp.op == And) jumpi = JUMP_IF_FALSE_OR_POP; else jumpi = JUMP_IF_TRUE_OR_POP; end = compiler_new_block(c); if (end == NULL) return 0; s = e->v.BoolOp.values; n = asdl_seq_LEN(s) - 1; assert(n >= 0); for (i = 0; i < n; ++i) { VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i)); ADDOP_JABS(c, jumpi, end); } VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n)); compiler_use_next_block(c, end); return 1; } static int starunpack_helper(struct compiler *c, asdl_seq *elts, int single_op, int inner_op, int outer_op) { Py_ssize_t n = asdl_seq_LEN(elts); Py_ssize_t i, nsubitems = 0, nseen = 0; for (i = 0; i < n; i++) { expr_ty elt = asdl_seq_GET(elts, i); if (elt->kind == Starred_kind) { if (nseen) { ADDOP_I(c, inner_op, nseen); nseen = 0; nsubitems++; } VISIT(c, expr, elt->v.Starred.value); nsubitems++; } else { VISIT(c, expr, elt); nseen++; } } if (nsubitems) { if (nseen) { ADDOP_I(c, inner_op, nseen); nsubitems++; } ADDOP_I(c, outer_op, nsubitems); } else ADDOP_I(c, single_op, nseen); return 1; } static int assignment_helper(struct compiler *c, asdl_seq *elts) { Py_ssize_t n = asdl_seq_LEN(elts); Py_ssize_t i; int seen_star = 0; for (i = 0; i < n; i++) { expr_ty elt = asdl_seq_GET(elts, i); if (elt->kind == Starred_kind && !seen_star) { if ((i >= (1 << 8)) || (n-i-1 >= (INT_MAX >> 8))) return compiler_error(c, "too many expressions in " "star-unpacking assignment"); ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); seen_star = 1; asdl_seq_SET(elts, i, elt->v.Starred.value); } else if (elt->kind == Starred_kind) { return compiler_error(c, "two starred expressions in assignment"); } } if (!seen_star) { ADDOP_I(c, UNPACK_SEQUENCE, n); } VISIT_SEQ(c, expr, elts); return 1; } static int compiler_list(struct compiler *c, expr_ty e) { asdl_seq *elts = e->v.List.elts; if (e->v.List.ctx == Store) { return assignment_helper(c, elts); } else if (e->v.List.ctx == Load) { return starunpack_helper(c, elts, BUILD_LIST, BUILD_TUPLE, BUILD_LIST_UNPACK); } else VISIT_SEQ(c, expr, elts); return 1; } static int compiler_tuple(struct compiler *c, expr_ty e) { asdl_seq *elts = e->v.Tuple.elts; if (e->v.Tuple.ctx == Store) { return assignment_helper(c, elts); } else if (e->v.Tuple.ctx == Load) { return starunpack_helper(c, elts, BUILD_TUPLE, BUILD_TUPLE, BUILD_TUPLE_UNPACK); } else VISIT_SEQ(c, expr, elts); return 1; } static int compiler_set(struct compiler *c, expr_ty e) { return starunpack_helper(c, e->v.Set.elts, BUILD_SET, BUILD_SET, BUILD_SET_UNPACK); } static int are_all_items_const(asdl_seq *seq, Py_ssize_t begin, Py_ssize_t end) { Py_ssize_t i; for (i = begin; i < end; i++) { expr_ty key = (expr_ty)asdl_seq_GET(seq, i); if (key == NULL || !is_const(key)) return 0; } return 1; } static int compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end) { Py_ssize_t i, n = end - begin; PyObject *keys, *key; if (n > 1 && are_all_items_const(e->v.Dict.keys, begin, end)) { for (i = begin; i < end; i++) { VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); } keys = PyTuple_New(n); if (keys == NULL) { return 0; } for (i = begin; i < end; i++) { key = get_const_value(c, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); Py_INCREF(key); PyTuple_SET_ITEM(keys, i - begin, key); } ADDOP_N(c, LOAD_CONST, keys, consts); ADDOP_I(c, BUILD_CONST_KEY_MAP, n); } else { for (i = begin; i < end; i++) { VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); } ADDOP_I(c, BUILD_MAP, n); } return 1; } static int compiler_dict(struct compiler *c, expr_ty e) { Py_ssize_t i, n, elements; int containers; int is_unpacking = 0; n = asdl_seq_LEN(e->v.Dict.values); containers = 0; elements = 0; for (i = 0; i < n; i++) { is_unpacking = (expr_ty)asdl_seq_GET(e->v.Dict.keys, i) == NULL; if (elements == 0xFFFF || (elements && is_unpacking)) { if (!compiler_subdict(c, e, i - elements, i)) return 0; containers++; elements = 0; } if (is_unpacking) { VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); containers++; } else { elements++; } } if (elements || containers == 0) { if (!compiler_subdict(c, e, n - elements, n)) return 0; containers++; } /* If there is more than one dict, they need to be merged into a new * dict. If there is one dict and it's an unpacking, then it needs * to be copied into a new dict." */ while (containers > 1 || is_unpacking) { int oparg = containers < 255 ? containers : 255; ADDOP_I(c, BUILD_MAP_UNPACK, oparg); containers -= (oparg - 1); is_unpacking = 0; } return 1; } static int compiler_compare(struct compiler *c, expr_ty e) { Py_ssize_t i, n; basicblock *cleanup = NULL; /* XXX the logic can be cleaned up for 1 or multiple comparisons */ VISIT(c, expr, e->v.Compare.left); n = asdl_seq_LEN(e->v.Compare.ops); assert(n > 0); if (n > 1) { cleanup = compiler_new_block(c); if (cleanup == NULL) return 0; VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0)); } for (i = 1; i < n; i++) { ADDOP(c, DUP_TOP); ADDOP(c, ROT_THREE); ADDOP_I(c, COMPARE_OP, cmpop((cmpop_ty)(asdl_seq_GET( e->v.Compare.ops, i - 1)))); ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup); NEXT_BLOCK(c); if (i < (n - 1)) VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i)); } VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1)); ADDOP_I(c, COMPARE_OP, cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1)))); if (n > 1) { basicblock *end = compiler_new_block(c); if (end == NULL) return 0; ADDOP_JREL(c, JUMP_FORWARD, end); compiler_use_next_block(c, cleanup); ADDOP(c, ROT_TWO); ADDOP(c, POP_TOP); compiler_use_next_block(c, end); } return 1; } // Return 1 if the method call was optimized, -1 if not, and 0 on error. static int maybe_optimize_method_call(struct compiler *c, expr_ty e) { Py_ssize_t argsl, i; expr_ty meth = e->v.Call.func; asdl_seq *args = e->v.Call.args; /* Check that the call node is an attribute access, and that the call doesn't have keyword parameters. */ if (meth->kind != Attribute_kind || meth->v.Attribute.ctx != Load || asdl_seq_LEN(e->v.Call.keywords)) return -1; /* Check that there are no *varargs types of arguments. */ argsl = asdl_seq_LEN(args); for (i = 0; i < argsl; i++) { expr_ty elt = asdl_seq_GET(args, i); if (elt->kind == Starred_kind) { return -1; } } /* Alright, we can optimize the code. */ VISIT(c, expr, meth->v.Attribute.value); ADDOP_NAME(c, LOAD_METHOD, meth->v.Attribute.attr, names); VISIT_SEQ(c, expr, e->v.Call.args); ADDOP_I(c, CALL_METHOD, asdl_seq_LEN(e->v.Call.args)); return 1; } static int compiler_call(struct compiler *c, expr_ty e) { int ret = maybe_optimize_method_call(c, e); if (ret >= 0) { return ret; } VISIT(c, expr, e->v.Call.func); return compiler_call_helper(c, 0, e->v.Call.args, e->v.Call.keywords); } static int compiler_joined_str(struct compiler *c, expr_ty e) { VISIT_SEQ(c, expr, e->v.JoinedStr.values); if (asdl_seq_LEN(e->v.JoinedStr.values) != 1) ADDOP_I(c, BUILD_STRING, asdl_seq_LEN(e->v.JoinedStr.values)); return 1; } /* Used to implement f-strings. Format a single value. */ static int compiler_formatted_value(struct compiler *c, expr_ty e) { /* Our oparg encodes 2 pieces of information: the conversion character, and whether or not a format_spec was provided. Convert the conversion char to 2 bits: None: 000 0x0 FVC_NONE !s : 001 0x1 FVC_STR !r : 010 0x2 FVC_REPR !a : 011 0x3 FVC_ASCII next bit is whether or not we have a format spec: yes : 100 0x4 no : 000 0x0 */ int oparg; /* Evaluate the expression to be formatted. */ VISIT(c, expr, e->v.FormattedValue.value); switch (e->v.FormattedValue.conversion) { case 's': oparg = FVC_STR; break; case 'r': oparg = FVC_REPR; break; case 'a': oparg = FVC_ASCII; break; case -1: oparg = FVC_NONE; break; default: PyErr_SetString(PyExc_SystemError, "Unrecognized conversion character"); return 0; } if (e->v.FormattedValue.format_spec) { /* Evaluate the format spec, and update our opcode arg. */ VISIT(c, expr, e->v.FormattedValue.format_spec); oparg |= FVS_HAVE_SPEC; } /* And push our opcode and oparg */ ADDOP_I(c, FORMAT_VALUE, oparg); return 1; } static int compiler_subkwargs(struct compiler *c, asdl_seq *keywords, Py_ssize_t begin, Py_ssize_t end) { Py_ssize_t i, n = end - begin; keyword_ty kw; PyObject *keys, *key; assert(n > 0); if (n > 1) { for (i = begin; i < end; i++) { kw = asdl_seq_GET(keywords, i); VISIT(c, expr, kw->value); } keys = PyTuple_New(n); if (keys == NULL) { return 0; } for (i = begin; i < end; i++) { key = ((keyword_ty) asdl_seq_GET(keywords, i))->arg; Py_INCREF(key); PyTuple_SET_ITEM(keys, i - begin, key); } ADDOP_N(c, LOAD_CONST, keys, consts); ADDOP_I(c, BUILD_CONST_KEY_MAP, n); } else { /* a for loop only executes once */ for (i = begin; i < end; i++) { kw = asdl_seq_GET(keywords, i); ADDOP_O(c, LOAD_CONST, kw->arg, consts); VISIT(c, expr, kw->value); } ADDOP_I(c, BUILD_MAP, n); } return 1; } /* shared code between compiler_call and compiler_class */ static int compiler_call_helper(struct compiler *c, int n, /* Args already pushed */ asdl_seq *args, asdl_seq *keywords) { Py_ssize_t i, nseen, nelts, nkwelts; int mustdictunpack = 0; /* the number of tuples and dictionaries on the stack */ Py_ssize_t nsubargs = 0, nsubkwargs = 0; nelts = asdl_seq_LEN(args); nkwelts = asdl_seq_LEN(keywords); for (i = 0; i < nkwelts; i++) { keyword_ty kw = asdl_seq_GET(keywords, i); if (kw->arg == NULL) { mustdictunpack = 1; break; } } nseen = n; /* the number of positional arguments on the stack */ for (i = 0; i < nelts; i++) { expr_ty elt = asdl_seq_GET(args, i); if (elt->kind == Starred_kind) { /* A star-arg. If we've seen positional arguments, pack the positional arguments into a tuple. */ if (nseen) { ADDOP_I(c, BUILD_TUPLE, nseen); nseen = 0; nsubargs++; } VISIT(c, expr, elt->v.Starred.value); nsubargs++; } else { VISIT(c, expr, elt); nseen++; } } /* Same dance again for keyword arguments */ if (nsubargs || mustdictunpack) { if (nseen) { /* Pack up any trailing positional arguments. */ ADDOP_I(c, BUILD_TUPLE, nseen); nsubargs++; } if (nsubargs > 1) { /* If we ended up with more than one stararg, we need to concatenate them into a single sequence. */ ADDOP_I(c, BUILD_TUPLE_UNPACK_WITH_CALL, nsubargs); } else if (nsubargs == 0) { ADDOP_I(c, BUILD_TUPLE, 0); } nseen = 0; /* the number of keyword arguments on the stack following */ for (i = 0; i < nkwelts; i++) { keyword_ty kw = asdl_seq_GET(keywords, i); if (kw->arg == NULL) { /* A keyword argument unpacking. */ if (nseen) { if (!compiler_subkwargs(c, keywords, i - nseen, i)) return 0; nsubkwargs++; nseen = 0; } VISIT(c, expr, kw->value); nsubkwargs++; } else { nseen++; } } if (nseen) { /* Pack up any trailing keyword arguments. */ if (!compiler_subkwargs(c, keywords, nkwelts - nseen, nkwelts)) return 0; nsubkwargs++; } if (nsubkwargs > 1) { /* Pack it all up */ ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs); } ADDOP_I(c, CALL_FUNCTION_EX, nsubkwargs > 0); return 1; } else if (nkwelts) { PyObject *names; VISIT_SEQ(c, keyword, keywords); names = PyTuple_New(nkwelts); if (names == NULL) { return 0; } for (i = 0; i < nkwelts; i++) { keyword_ty kw = asdl_seq_GET(keywords, i); Py_INCREF(kw->arg); PyTuple_SET_ITEM(names, i, kw->arg); } ADDOP_N(c, LOAD_CONST, names, consts); ADDOP_I(c, CALL_FUNCTION_KW, n + nelts + nkwelts); return 1; } else { ADDOP_I(c, CALL_FUNCTION, n + nelts); return 1; } } /* List and set comprehensions and generator expressions work by creating a nested function to perform the actual iteration. This means that the iteration variables don't leak into the current scope. The defined function is called immediately following its definition, with the result of that call being the result of the expression. The LC/SC version returns the populated container, while the GE version is flagged in symtable.c as a generator, so it returns the generator object when the function is called. This code *knows* that the loop cannot contain break, continue, or return, so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops. Possible cleanups: - iterate over the generator sequence instead of using recursion */ static int compiler_comprehension_generator(struct compiler *c, asdl_seq *generators, int gen_index, expr_ty elt, expr_ty val, int type) { comprehension_ty gen; gen = (comprehension_ty)asdl_seq_GET(generators, gen_index); if (gen->is_async) { return compiler_async_comprehension_generator( c, generators, gen_index, elt, val, type); } else { return compiler_sync_comprehension_generator( c, generators, gen_index, elt, val, type); } } static int compiler_sync_comprehension_generator(struct compiler *c, asdl_seq *generators, int gen_index, expr_ty elt, expr_ty val, int type) { /* generate code for the iterator, then each of the ifs, and then write to the element */ comprehension_ty gen; basicblock *start, *anchor, *skip, *if_cleanup; Py_ssize_t i, n; start = compiler_new_block(c); skip = compiler_new_block(c); if_cleanup = compiler_new_block(c); anchor = compiler_new_block(c); if (start == NULL || skip == NULL || if_cleanup == NULL || anchor == NULL) return 0; gen = (comprehension_ty)asdl_seq_GET(generators, gen_index); if (gen_index == 0) { /* Receive outermost iter as an implicit argument */ c->u->u_argcount = 1; ADDOP_I(c, LOAD_FAST, 0); } else { /* Sub-iter - calculate on the fly */ VISIT(c, expr, gen->iter); ADDOP(c, GET_ITER); } compiler_use_next_block(c, start); ADDOP_JREL(c, FOR_ITER, anchor); NEXT_BLOCK(c); VISIT(c, expr, gen->target); /* XXX this needs to be cleaned up...a lot! */ n = asdl_seq_LEN(gen->ifs); for (i = 0; i < n; i++) { expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i); VISIT(c, expr, e); ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup); NEXT_BLOCK(c); } if (++gen_index < asdl_seq_LEN(generators)) if (!compiler_comprehension_generator(c, generators, gen_index, elt, val, type)) return 0; /* only append after the last for generator */ if (gen_index >= asdl_seq_LEN(generators)) { /* comprehension specific code */ switch (type) { case COMP_GENEXP: VISIT(c, expr, elt); ADDOP(c, YIELD_VALUE); ADDOP(c, POP_TOP); break; case COMP_LISTCOMP: VISIT(c, expr, elt); ADDOP_I(c, LIST_APPEND, gen_index + 1); break; case COMP_SETCOMP: VISIT(c, expr, elt); ADDOP_I(c, SET_ADD, gen_index + 1); break; case COMP_DICTCOMP: /* With 'd[k] = v', v is evaluated before k, so we do the same. */ VISIT(c, expr, val); VISIT(c, expr, elt); ADDOP_I(c, MAP_ADD, gen_index + 1); break; default: return 0; } compiler_use_next_block(c, skip); } compiler_use_next_block(c, if_cleanup); ADDOP_JABS(c, JUMP_ABSOLUTE, start); compiler_use_next_block(c, anchor); return 1; } static int compiler_async_comprehension_generator(struct compiler *c, asdl_seq *generators, int gen_index, expr_ty elt, expr_ty val, int type) { _Py_IDENTIFIER(StopAsyncIteration); comprehension_ty gen; basicblock *if_cleanup, *try, *after_try, *except, *try_cleanup; Py_ssize_t i, n; PyObject *stop_aiter_error = _PyUnicode_FromId(&PyId_StopAsyncIteration); if (stop_aiter_error == NULL) { return 0; } try = compiler_new_block(c); after_try = compiler_new_block(c); except = compiler_new_block(c); if_cleanup = compiler_new_block(c); try_cleanup = compiler_new_block(c); if (if_cleanup == NULL || try == NULL || after_try == NULL || except == NULL || try_cleanup == NULL) { return 0; } gen = (comprehension_ty)asdl_seq_GET(generators, gen_index); if (gen_index == 0) { /* Receive outermost iter as an implicit argument */ c->u->u_argcount = 1; ADDOP_I(c, LOAD_FAST, 0); } else { /* Sub-iter - calculate on the fly */ VISIT(c, expr, gen->iter); ADDOP(c, GET_AITER); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, YIELD_FROM); } compiler_use_next_block(c, try); ADDOP_JREL(c, SETUP_EXCEPT, except); if (!compiler_push_fblock(c, EXCEPT, try)) return 0; ADDOP(c, GET_ANEXT); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, YIELD_FROM); VISIT(c, expr, gen->target); ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, EXCEPT, try); ADDOP_JREL(c, JUMP_FORWARD, after_try); compiler_use_next_block(c, except); ADDOP(c, DUP_TOP); ADDOP_O(c, LOAD_GLOBAL, stop_aiter_error, names); ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH); ADDOP_JABS(c, POP_JUMP_IF_TRUE, try_cleanup); ADDOP(c, END_FINALLY); compiler_use_next_block(c, after_try); n = asdl_seq_LEN(gen->ifs); for (i = 0; i < n; i++) { expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i); VISIT(c, expr, e); ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup); NEXT_BLOCK(c); } if (++gen_index < asdl_seq_LEN(generators)) if (!compiler_comprehension_generator(c, generators, gen_index, elt, val, type)) return 0; /* only append after the last for generator */ if (gen_index >= asdl_seq_LEN(generators)) { /* comprehension specific code */ switch (type) { case COMP_GENEXP: VISIT(c, expr, elt); ADDOP(c, YIELD_VALUE); ADDOP(c, POP_TOP); break; case COMP_LISTCOMP: VISIT(c, expr, elt); ADDOP_I(c, LIST_APPEND, gen_index + 1); break; case COMP_SETCOMP: VISIT(c, expr, elt); ADDOP_I(c, SET_ADD, gen_index + 1); break; case COMP_DICTCOMP: /* With 'd[k] = v', v is evaluated before k, so we do the same. */ VISIT(c, expr, val); VISIT(c, expr, elt); ADDOP_I(c, MAP_ADD, gen_index + 1); break; default: return 0; } } compiler_use_next_block(c, if_cleanup); ADDOP_JABS(c, JUMP_ABSOLUTE, try); compiler_use_next_block(c, try_cleanup); ADDOP(c, POP_TOP); ADDOP(c, POP_TOP); ADDOP(c, POP_TOP); ADDOP(c, POP_EXCEPT); /* for SETUP_EXCEPT */ ADDOP(c, POP_TOP); return 1; } static int compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name, asdl_seq *generators, expr_ty elt, expr_ty val) { PyCodeObject *co = NULL; comprehension_ty outermost; PyObject *qualname = NULL; int is_async_function = c->u->u_ste->ste_coroutine; int is_async_generator = 0; outermost = (comprehension_ty) asdl_seq_GET(generators, 0); if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION, (void *)e, e->lineno)) { goto error; } is_async_generator = c->u->u_ste->ste_coroutine; if (is_async_generator && !is_async_function) { if (e->lineno > c->u->u_lineno) { c->u->u_lineno = e->lineno; c->u->u_lineno_set = 0; } compiler_error(c, "asynchronous comprehension outside of " "an asynchronous function"); goto error_in_scope; } if (type != COMP_GENEXP) { int op; switch (type) { case COMP_LISTCOMP: op = BUILD_LIST; break; case COMP_SETCOMP: op = BUILD_SET; break; case COMP_DICTCOMP: op = BUILD_MAP; break; default: PyErr_Format(PyExc_SystemError, "unknown comprehension type %d", type); goto error_in_scope; } ADDOP_I(c, op, 0); } if (!compiler_comprehension_generator(c, generators, 0, elt, val, type)) goto error_in_scope; if (type != COMP_GENEXP) { ADDOP(c, RETURN_VALUE); } co = assemble(c, 1); qualname = c->u->u_qualname; Py_INCREF(qualname); compiler_exit_scope(c); if (co == NULL) goto error; if (!compiler_make_closure(c, co, 0, qualname)) goto error; Py_DECREF(qualname); Py_DECREF(co); VISIT(c, expr, outermost->iter); if (outermost->is_async) { ADDOP(c, GET_AITER); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, YIELD_FROM); } else { ADDOP(c, GET_ITER); } ADDOP_I(c, CALL_FUNCTION, 1); if (is_async_generator && type != COMP_GENEXP) { ADDOP(c, GET_AWAITABLE); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, YIELD_FROM); } return 1; error_in_scope: compiler_exit_scope(c); error: Py_XDECREF(qualname); Py_XDECREF(co); return 0; } static int compiler_genexp(struct compiler *c, expr_ty e) { static identifier name; if (!name) { name = PyUnicode_FromString("<genexpr>"); if (!name) return 0; } assert(e->kind == GeneratorExp_kind); return compiler_comprehension(c, e, COMP_GENEXP, name, e->v.GeneratorExp.generators, e->v.GeneratorExp.elt, NULL); } static int compiler_listcomp(struct compiler *c, expr_ty e) { static identifier name; if (!name) { name = PyUnicode_FromString("<listcomp>"); if (!name) return 0; } assert(e->kind == ListComp_kind); return compiler_comprehension(c, e, COMP_LISTCOMP, name, e->v.ListComp.generators, e->v.ListComp.elt, NULL); } static int compiler_setcomp(struct compiler *c, expr_ty e) { static identifier name; if (!name) { name = PyUnicode_FromString("<setcomp>"); if (!name) return 0; } assert(e->kind == SetComp_kind); return compiler_comprehension(c, e, COMP_SETCOMP, name, e->v.SetComp.generators, e->v.SetComp.elt, NULL); } static int compiler_dictcomp(struct compiler *c, expr_ty e) { static identifier name; if (!name) { name = PyUnicode_FromString("<dictcomp>"); if (!name) return 0; } assert(e->kind == DictComp_kind); return compiler_comprehension(c, e, COMP_DICTCOMP, name, e->v.DictComp.generators, e->v.DictComp.key, e->v.DictComp.value); } static int compiler_visit_keyword(struct compiler *c, keyword_ty k) { VISIT(c, expr, k->value); return 1; } /* Test whether expression is constant. For constants, report whether they are true or false. Return values: 1 for true, 0 for false, -1 for non-constant. */ static int expr_constant(struct compiler *c, expr_ty e) { if (is_const(e)) { return PyObject_IsTrue(get_const_value(c, e)); } return -1; } /* Implements the async with statement. The semantics outlined in that PEP are as follows: async with EXPR as VAR: BLOCK It is implemented roughly as: context = EXPR exit = context.__aexit__ # not calling it value = await context.__aenter__() try: VAR = value # if VAR present in the syntax BLOCK finally: if an exception was raised: exc = copy of (exception, instance, traceback) else: exc = (None, None, None) if not (await exit(*exc)): raise */ static int compiler_async_with(struct compiler *c, stmt_ty s, int pos) { basicblock *block, *finally; withitem_ty item = asdl_seq_GET(s->v.AsyncWith.items, pos); assert(s->kind == AsyncWith_kind); block = compiler_new_block(c); finally = compiler_new_block(c); if (!block || !finally) return 0; /* Evaluate EXPR */ VISIT(c, expr, item->context_expr); ADDOP(c, BEFORE_ASYNC_WITH); ADDOP(c, GET_AWAITABLE); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, YIELD_FROM); ADDOP_JREL(c, SETUP_ASYNC_WITH, finally); /* SETUP_ASYNC_WITH pushes a finally block. */ compiler_use_next_block(c, block); if (!compiler_push_fblock(c, FINALLY_TRY, block)) { return 0; } if (item->optional_vars) { VISIT(c, expr, item->optional_vars); } else { /* Discard result from context.__aenter__() */ ADDOP(c, POP_TOP); } pos++; if (pos == asdl_seq_LEN(s->v.AsyncWith.items)) /* BLOCK code */ VISIT_SEQ(c, stmt, s->v.AsyncWith.body) else if (!compiler_async_with(c, s, pos)) return 0; /* End of try block; start the finally block */ ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, FINALLY_TRY, block); ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_use_next_block(c, finally); if (!compiler_push_fblock(c, FINALLY_END, finally)) return 0; /* Finally block starts; context.__exit__ is on the stack under the exception or return information. Just issue our magic opcode. */ ADDOP(c, WITH_CLEANUP_START); ADDOP(c, GET_AWAITABLE); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, YIELD_FROM); ADDOP(c, WITH_CLEANUP_FINISH); /* Finally block ends. */ ADDOP(c, END_FINALLY); compiler_pop_fblock(c, FINALLY_END, finally); return 1; } /* Implements the with statement from PEP 343. The semantics outlined in that PEP are as follows: with EXPR as VAR: BLOCK It is implemented roughly as: context = EXPR exit = context.__exit__ # not calling it value = context.__enter__() try: VAR = value # if VAR present in the syntax BLOCK finally: if an exception was raised: exc = copy of (exception, instance, traceback) else: exc = (None, None, None) exit(*exc) */ static int compiler_with(struct compiler *c, stmt_ty s, int pos) { basicblock *block, *finally; withitem_ty item = asdl_seq_GET(s->v.With.items, pos); assert(s->kind == With_kind); block = compiler_new_block(c); finally = compiler_new_block(c); if (!block || !finally) return 0; /* Evaluate EXPR */ VISIT(c, expr, item->context_expr); ADDOP_JREL(c, SETUP_WITH, finally); /* SETUP_WITH pushes a finally block. */ compiler_use_next_block(c, block); if (!compiler_push_fblock(c, FINALLY_TRY, block)) { return 0; } if (item->optional_vars) { VISIT(c, expr, item->optional_vars); } else { /* Discard result from context.__enter__() */ ADDOP(c, POP_TOP); } pos++; if (pos == asdl_seq_LEN(s->v.With.items)) /* BLOCK code */ VISIT_SEQ(c, stmt, s->v.With.body) else if (!compiler_with(c, s, pos)) return 0; /* End of try block; start the finally block */ ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, FINALLY_TRY, block); ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_use_next_block(c, finally); if (!compiler_push_fblock(c, FINALLY_END, finally)) return 0; /* Finally block starts; context.__exit__ is on the stack under the exception or return information. Just issue our magic opcode. */ ADDOP(c, WITH_CLEANUP_START); ADDOP(c, WITH_CLEANUP_FINISH); /* Finally block ends. */ ADDOP(c, END_FINALLY); compiler_pop_fblock(c, FINALLY_END, finally); return 1; } static int compiler_visit_expr(struct compiler *c, expr_ty e) { /* If expr e has a different line number than the last expr/stmt, set a new line number for the next instruction. */ if (e->lineno > c->u->u_lineno) { c->u->u_lineno = e->lineno; c->u->u_lineno_set = 0; } /* Updating the column offset is always harmless. */ c->u->u_col_offset = e->col_offset; switch (e->kind) { case BoolOp_kind: return compiler_boolop(c, e); case BinOp_kind: VISIT(c, expr, e->v.BinOp.left); VISIT(c, expr, e->v.BinOp.right); ADDOP(c, binop(c, e->v.BinOp.op)); break; case UnaryOp_kind: VISIT(c, expr, e->v.UnaryOp.operand); ADDOP(c, unaryop(e->v.UnaryOp.op)); break; case Lambda_kind: return compiler_lambda(c, e); case IfExp_kind: return compiler_ifexp(c, e); case Dict_kind: return compiler_dict(c, e); case Set_kind: return compiler_set(c, e); case GeneratorExp_kind: return compiler_genexp(c, e); case ListComp_kind: return compiler_listcomp(c, e); case SetComp_kind: return compiler_setcomp(c, e); case DictComp_kind: return compiler_dictcomp(c, e); case Yield_kind: if (c->u->u_ste->ste_type != FunctionBlock) return compiler_error(c, "'yield' outside function"); if (e->v.Yield.value) { VISIT(c, expr, e->v.Yield.value); } else { ADDOP_O(c, LOAD_CONST, Py_None, consts); } ADDOP(c, YIELD_VALUE); break; case YieldFrom_kind: if (c->u->u_ste->ste_type != FunctionBlock) return compiler_error(c, "'yield' outside function"); if (c->u->u_scope_type == COMPILER_SCOPE_ASYNC_FUNCTION) return compiler_error(c, "'yield from' inside async function"); VISIT(c, expr, e->v.YieldFrom.value); ADDOP(c, GET_YIELD_FROM_ITER); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, YIELD_FROM); break; case Await_kind: if (c->u->u_ste->ste_type != FunctionBlock) return compiler_error(c, "'await' outside function"); if (c->u->u_scope_type != COMPILER_SCOPE_ASYNC_FUNCTION && c->u->u_scope_type != COMPILER_SCOPE_COMPREHENSION) return compiler_error(c, "'await' outside async function"); VISIT(c, expr, e->v.Await.value); ADDOP(c, GET_AWAITABLE); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, YIELD_FROM); break; case Compare_kind: return compiler_compare(c, e); case Call_kind: return compiler_call(c, e); case Constant_kind: ADDOP_O(c, LOAD_CONST, e->v.Constant.value, consts); break; case Num_kind: ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts); break; case Str_kind: ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts); break; case JoinedStr_kind: return compiler_joined_str(c, e); case FormattedValue_kind: return compiler_formatted_value(c, e); case Bytes_kind: ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts); break; case Ellipsis_kind: ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts); break; case NameConstant_kind: ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts); break; /* The following exprs can be assignment targets. */ case Attribute_kind: if (e->v.Attribute.ctx != AugStore) VISIT(c, expr, e->v.Attribute.value); switch (e->v.Attribute.ctx) { case AugLoad: ADDOP(c, DUP_TOP); /* Fall through */ case Load: ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names); break; case AugStore: ADDOP(c, ROT_TWO); /* Fall through */ case Store: ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names); break; case Del: ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names); break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid in attribute expression"); return 0; } break; case Subscript_kind: switch (e->v.Subscript.ctx) { case AugLoad: VISIT(c, expr, e->v.Subscript.value); VISIT_SLICE(c, e->v.Subscript.slice, AugLoad); break; case Load: VISIT(c, expr, e->v.Subscript.value); VISIT_SLICE(c, e->v.Subscript.slice, Load); break; case AugStore: VISIT_SLICE(c, e->v.Subscript.slice, AugStore); break; case Store: VISIT(c, expr, e->v.Subscript.value); VISIT_SLICE(c, e->v.Subscript.slice, Store); break; case Del: VISIT(c, expr, e->v.Subscript.value); VISIT_SLICE(c, e->v.Subscript.slice, Del); break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid in subscript expression"); return 0; } break; case Starred_kind: switch (e->v.Starred.ctx) { case Store: /* In all legitimate cases, the Starred node was already replaced * by compiler_list/compiler_tuple. XXX: is that okay? */ return compiler_error(c, "starred assignment target must be in a list or tuple"); default: return compiler_error(c, "can't use starred expression here"); } break; case Name_kind: return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx); /* child nodes of List and Tuple will have expr_context set */ case List_kind: return compiler_list(c, e); case Tuple_kind: return compiler_tuple(c, e); } return 1; } static int compiler_augassign(struct compiler *c, stmt_ty s) { expr_ty e = s->v.AugAssign.target; expr_ty auge; assert(s->kind == AugAssign_kind); switch (e->kind) { case Attribute_kind: auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr, AugLoad, e->lineno, e->col_offset, c->c_arena); if (auge == NULL) return 0; VISIT(c, expr, auge); VISIT(c, expr, s->v.AugAssign.value); ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); auge->v.Attribute.ctx = AugStore; VISIT(c, expr, auge); break; case Subscript_kind: auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice, AugLoad, e->lineno, e->col_offset, c->c_arena); if (auge == NULL) return 0; VISIT(c, expr, auge); VISIT(c, expr, s->v.AugAssign.value); ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); auge->v.Subscript.ctx = AugStore; VISIT(c, expr, auge); break; case Name_kind: if (!compiler_nameop(c, e->v.Name.id, Load)) return 0; VISIT(c, expr, s->v.AugAssign.value); ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); return compiler_nameop(c, e->v.Name.id, Store); default: PyErr_Format(PyExc_SystemError, "invalid node type (%d) for augmented assignment", e->kind); return 0; } return 1; } static int check_ann_expr(struct compiler *c, expr_ty e) { VISIT(c, expr, e); ADDOP(c, POP_TOP); return 1; } static int check_annotation(struct compiler *c, stmt_ty s) { /* Annotations are only evaluated in a module or class. */ if (c->u->u_scope_type == COMPILER_SCOPE_MODULE || c->u->u_scope_type == COMPILER_SCOPE_CLASS) { return check_ann_expr(c, s->v.AnnAssign.annotation); } return 1; } static int check_ann_slice(struct compiler *c, slice_ty sl) { switch(sl->kind) { case Index_kind: return check_ann_expr(c, sl->v.Index.value); case Slice_kind: if (sl->v.Slice.lower && !check_ann_expr(c, sl->v.Slice.lower)) { return 0; } if (sl->v.Slice.upper && !check_ann_expr(c, sl->v.Slice.upper)) { return 0; } if (sl->v.Slice.step && !check_ann_expr(c, sl->v.Slice.step)) { return 0; } break; default: PyErr_SetString(PyExc_SystemError, "unexpected slice kind"); return 0; } return 1; } static int check_ann_subscr(struct compiler *c, slice_ty sl) { /* We check that everything in a subscript is defined at runtime. */ Py_ssize_t i, n; switch (sl->kind) { case Index_kind: case Slice_kind: if (!check_ann_slice(c, sl)) { return 0; } break; case ExtSlice_kind: n = asdl_seq_LEN(sl->v.ExtSlice.dims); for (i = 0; i < n; i++) { slice_ty subsl = (slice_ty)asdl_seq_GET(sl->v.ExtSlice.dims, i); switch (subsl->kind) { case Index_kind: case Slice_kind: if (!check_ann_slice(c, subsl)) { return 0; } break; case ExtSlice_kind: default: PyErr_SetString(PyExc_SystemError, "extended slice invalid in nested slice"); return 0; } } break; default: PyErr_Format(PyExc_SystemError, "invalid subscript kind %d", sl->kind); return 0; } return 1; } static int compiler_annassign(struct compiler *c, stmt_ty s) { expr_ty targ = s->v.AnnAssign.target; PyObject* mangled; assert(s->kind == AnnAssign_kind); /* We perform the actual assignment first. */ if (s->v.AnnAssign.value) { VISIT(c, expr, s->v.AnnAssign.value); VISIT(c, expr, targ); } switch (targ->kind) { case Name_kind: /* If we have a simple name in a module or class, store annotation. */ if (s->v.AnnAssign.simple && (c->u->u_scope_type == COMPILER_SCOPE_MODULE || c->u->u_scope_type == COMPILER_SCOPE_CLASS)) { VISIT(c, expr, s->v.AnnAssign.annotation); mangled = _Py_Mangle(c->u->u_private, targ->v.Name.id); if (!mangled) { return 0; } /* ADDOP_N decrefs its argument */ ADDOP_N(c, STORE_ANNOTATION, mangled, names); } break; case Attribute_kind: if (!s->v.AnnAssign.value && !check_ann_expr(c, targ->v.Attribute.value)) { return 0; } break; case Subscript_kind: if (!s->v.AnnAssign.value && (!check_ann_expr(c, targ->v.Subscript.value) || !check_ann_subscr(c, targ->v.Subscript.slice))) { return 0; } break; default: PyErr_Format(PyExc_SystemError, "invalid node type (%d) for annotated assignment", targ->kind); return 0; } /* Annotation is evaluated last. */ if (!s->v.AnnAssign.simple && !check_annotation(c, s)) { return 0; } return 1; } static int compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { struct fblockinfo *f; if (c->u->u_nfblocks >= CO_MAXBLOCKS) { PyErr_SetString(PyExc_SyntaxError, "too many statically nested blocks"); return 0; } f = &c->u->u_fblock[c->u->u_nfblocks++]; f->fb_type = t; f->fb_block = b; return 1; } static void compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { struct compiler_unit *u = c->u; assert(u->u_nfblocks > 0); u->u_nfblocks--; assert(u->u_fblock[u->u_nfblocks].fb_type == t); assert(u->u_fblock[u->u_nfblocks].fb_block == b); } static int compiler_in_loop(struct compiler *c) { int i; struct compiler_unit *u = c->u; for (i = 0; i < u->u_nfblocks; ++i) { if (u->u_fblock[i].fb_type == LOOP) return 1; } return 0; } /* Raises a SyntaxError and returns 0. If something goes wrong, a different exception may be raised. */ static int compiler_error(struct compiler *c, const char *errstr) { PyObject *loc; PyObject *u = NULL, *v = NULL; loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno); if (!loc) { Py_INCREF(Py_None); loc = Py_None; } u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno, c->u->u_col_offset, loc); if (!u) goto exit; v = Py_BuildValue("(zO)", errstr, u); if (!v) goto exit; PyErr_SetObject(PyExc_SyntaxError, v); exit: Py_DECREF(loc); Py_XDECREF(u); Py_XDECREF(v); return 0; } static int compiler_handle_subscr(struct compiler *c, const char *kind, expr_context_ty ctx) { int op = 0; /* XXX this code is duplicated */ switch (ctx) { case AugLoad: /* fall through to Load */ case Load: op = BINARY_SUBSCR; break; case AugStore:/* fall through to Store */ case Store: op = STORE_SUBSCR; break; case Del: op = DELETE_SUBSCR; break; case Param: PyErr_Format(PyExc_SystemError, "invalid %s kind %d in subscript\n", kind, ctx); return 0; } if (ctx == AugLoad) { ADDOP(c, DUP_TOP_TWO); } else if (ctx == AugStore) { ADDOP(c, ROT_THREE); } ADDOP(c, op); return 1; } static int compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { int n = 2; assert(s->kind == Slice_kind); /* only handles the cases where BUILD_SLICE is emitted */ if (s->v.Slice.lower) { VISIT(c, expr, s->v.Slice.lower); } else { ADDOP_O(c, LOAD_CONST, Py_None, consts); } if (s->v.Slice.upper) { VISIT(c, expr, s->v.Slice.upper); } else { ADDOP_O(c, LOAD_CONST, Py_None, consts); } if (s->v.Slice.step) { n++; VISIT(c, expr, s->v.Slice.step); } ADDOP_I(c, BUILD_SLICE, n); return 1; } static int compiler_visit_nested_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { switch (s->kind) { case Slice_kind: return compiler_slice(c, s, ctx); case Index_kind: VISIT(c, expr, s->v.Index.value); break; case ExtSlice_kind: default: PyErr_SetString(PyExc_SystemError, "extended slice invalid in nested slice"); return 0; } return 1; } static int compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { char * kindname = NULL; switch (s->kind) { case Index_kind: kindname = "index"; if (ctx != AugStore) { VISIT(c, expr, s->v.Index.value); } break; case Slice_kind: kindname = "slice"; if (ctx != AugStore) { if (!compiler_slice(c, s, ctx)) return 0; } break; case ExtSlice_kind: kindname = "extended slice"; if (ctx != AugStore) { Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims); for (i = 0; i < n; i++) { slice_ty sub = (slice_ty)asdl_seq_GET( s->v.ExtSlice.dims, i); if (!compiler_visit_nested_slice(c, sub, ctx)) return 0; } ADDOP_I(c, BUILD_TUPLE, n); } break; default: PyErr_Format(PyExc_SystemError, "invalid subscript kind %d", s->kind); return 0; } return compiler_handle_subscr(c, kindname, ctx); } /* End of the compiler section, beginning of the assembler section */ /* do depth-first search of basic block graph, starting with block. post records the block indices in post-order. XXX must handle implicit jumps from one block to next */ struct assembler { PyObject *a_bytecode; /* string containing bytecode */ int a_offset; /* offset into bytecode */ int a_nblocks; /* number of reachable blocks */ basicblock **a_postorder; /* list of blocks in dfs postorder */ PyObject *a_lnotab; /* string containing lnotab */ int a_lnotab_off; /* offset into lnotab */ int a_lineno; /* last lineno of emitted instruction */ int a_lineno_off; /* bytecode offset of last lineno */ }; static void dfs(struct compiler *c, basicblock *b, struct assembler *a) { int i; struct instr *instr = NULL; if (b->b_seen) return; b->b_seen = 1; if (b->b_next != NULL) dfs(c, b->b_next, a); for (i = 0; i < b->b_iused; i++) { instr = &b->b_instr[i]; if (instr->i_jrel || instr->i_jabs) dfs(c, instr->i_target, a); } a->a_postorder[a->a_nblocks++] = b; } static int stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth) { int i, target_depth, effect; struct instr *instr; if (b->b_seen || b->b_startdepth >= depth) return maxdepth; b->b_seen = 1; b->b_startdepth = depth; for (i = 0; i < b->b_iused; i++) { instr = &b->b_instr[i]; effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg); if (effect == PY_INVALID_STACK_EFFECT) { fprintf(stderr, "opcode = %d\n", instr->i_opcode); Py_FatalError("PyCompile_OpcodeStackEffect()"); } depth += effect; if (depth > maxdepth) maxdepth = depth; assert(depth >= 0); /* invalid code or bug in stackdepth() */ if (instr->i_jrel || instr->i_jabs) { target_depth = depth; if (instr->i_opcode == FOR_ITER) { target_depth = depth-2; } else if (instr->i_opcode == SETUP_FINALLY || instr->i_opcode == SETUP_EXCEPT) { target_depth = depth+3; if (target_depth > maxdepth) maxdepth = target_depth; } else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP || instr->i_opcode == JUMP_IF_FALSE_OR_POP) depth = depth - 1; maxdepth = stackdepth_walk(c, instr->i_target, target_depth, maxdepth); if (instr->i_opcode == JUMP_ABSOLUTE || instr->i_opcode == JUMP_FORWARD) { goto out; /* remaining code is dead */ } } } if (b->b_next) maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth); out: b->b_seen = 0; return maxdepth; } /* Find the flow path that needs the largest stack. We assume that * cycles in the flow graph have no net effect on the stack depth. */ static int stackdepth(struct compiler *c) { basicblock *b, *entryblock; entryblock = NULL; for (b = c->u->u_blocks; b != NULL; b = b->b_list) { b->b_seen = 0; b->b_startdepth = INT_MIN; entryblock = b; } if (!entryblock) return 0; return stackdepth_walk(c, entryblock, 0, 0); } static int assemble_init(struct assembler *a, int nblocks, int firstlineno) { bzero(a, sizeof(struct assembler)); a->a_lineno = firstlineno; a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE); if (!a->a_bytecode) return 0; a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE); if (!a->a_lnotab) return 0; if ((size_t)nblocks > SIZE_MAX / sizeof(basicblock *)) { PyErr_NoMemory(); return 0; } a->a_postorder = (basicblock **)PyObject_Malloc( sizeof(basicblock *) * nblocks); if (!a->a_postorder) { PyErr_NoMemory(); return 0; } return 1; } static void assemble_free(struct assembler *a) { Py_XDECREF(a->a_bytecode); Py_XDECREF(a->a_lnotab); if (a->a_postorder) PyObject_Free(a->a_postorder); } static int blocksize(basicblock *b) { int i; int size = 0; for (i = 0; i < b->b_iused; i++) size += instrsize(b->b_instr[i].i_oparg); return size; } /* Appends a pair to the end of the line number table, a_lnotab, representing the instruction's bytecode offset and line number. See Objects/lnotab_notes.txt for the description of the line number table. */ static int assemble_lnotab(struct assembler *a, struct instr *i) { int d_bytecode, d_lineno; Py_ssize_t len; unsigned char *lnotab; d_bytecode = (a->a_offset - a->a_lineno_off) * sizeof(_Py_CODEUNIT); d_lineno = i->i_lineno - a->a_lineno; assert(d_bytecode >= 0); if(d_bytecode == 0 && d_lineno == 0) return 1; if (d_bytecode > 255) { int j, nbytes, ncodes = d_bytecode / 255; nbytes = a->a_lnotab_off + 2 * ncodes; len = PyBytes_GET_SIZE(a->a_lnotab); if (nbytes >= len) { if ((len <= INT_MAX / 2) && (len * 2 < nbytes)) len = nbytes; else if (len <= INT_MAX / 2) len *= 2; else { PyErr_NoMemory(); return 0; } if (_PyBytes_Resize(&a->a_lnotab, len) < 0) return 0; } lnotab = (unsigned char *) PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; for (j = 0; j < ncodes; j++) { *lnotab++ = 255; *lnotab++ = 0; } d_bytecode -= ncodes * 255; a->a_lnotab_off += ncodes * 2; } assert(0 <= d_bytecode && d_bytecode <= 255); if (d_lineno < -128 || 127 < d_lineno) { int j, nbytes, ncodes, k; if (d_lineno < 0) { k = -128; /* use division on positive numbers */ ncodes = (-d_lineno) / 128; } else { k = 127; ncodes = d_lineno / 127; } d_lineno -= ncodes * k; assert(ncodes >= 1); nbytes = a->a_lnotab_off + 2 * ncodes; len = PyBytes_GET_SIZE(a->a_lnotab); if (nbytes >= len) { if ((len <= INT_MAX / 2) && len * 2 < nbytes) len = nbytes; else if (len <= INT_MAX / 2) len *= 2; else { PyErr_NoMemory(); return 0; } if (_PyBytes_Resize(&a->a_lnotab, len) < 0) return 0; } lnotab = (unsigned char *) PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; *lnotab++ = d_bytecode; *lnotab++ = k; d_bytecode = 0; for (j = 1; j < ncodes; j++) { *lnotab++ = 0; *lnotab++ = k; } a->a_lnotab_off += ncodes * 2; } assert(-128 <= d_lineno && d_lineno <= 127); len = PyBytes_GET_SIZE(a->a_lnotab); if (a->a_lnotab_off + 2 >= len) { if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0) return 0; } lnotab = (unsigned char *) PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; a->a_lnotab_off += 2; if (d_bytecode) { *lnotab++ = d_bytecode; *lnotab++ = d_lineno; } else { /* First line of a block; def stmt, etc. */ *lnotab++ = 0; *lnotab++ = d_lineno; } a->a_lineno = i->i_lineno; a->a_lineno_off = a->a_offset; return 1; } /* assemble_emit() Extend the bytecode with a new instruction. Update lnotab if necessary. */ static int assemble_emit(struct assembler *a, struct instr *i) { int size, arg = 0; Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode); _Py_CODEUNIT *code; arg = i->i_oparg; size = instrsize(arg); if (i->i_lineno && !assemble_lnotab(a, i)) return 0; if (a->a_offset + size >= len / (int)sizeof(_Py_CODEUNIT)) { if (len > PY_SSIZE_T_MAX / 2) return 0; if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0) return 0; } code = (_Py_CODEUNIT *)PyBytes_AS_STRING(a->a_bytecode) + a->a_offset; a->a_offset += size; write_op_arg(code, i->i_opcode, arg, size); return 1; } static void assemble_jump_offsets(struct assembler *a, struct compiler *c) { basicblock *b; int bsize, totsize, extended_arg_recompile; int i; /* Compute the size of each block and fixup jump args. Replace block pointer with position in bytecode. */ do { totsize = 0; for (i = a->a_nblocks - 1; i >= 0; i--) { b = a->a_postorder[i]; bsize = blocksize(b); b->b_offset = totsize; totsize += bsize; } extended_arg_recompile = 0; for (b = c->u->u_blocks; b != NULL; b = b->b_list) { bsize = b->b_offset; for (i = 0; i < b->b_iused; i++) { struct instr *instr = &b->b_instr[i]; int isize = instrsize(instr->i_oparg); /* Relative jumps are computed relative to the instruction pointer after fetching the jump instruction. */ bsize += isize; if (instr->i_jabs || instr->i_jrel) { instr->i_oparg = instr->i_target->b_offset; if (instr->i_jrel) { instr->i_oparg -= bsize; } instr->i_oparg *= sizeof(_Py_CODEUNIT); if (instrsize(instr->i_oparg) != isize) { extended_arg_recompile = 1; } } } } /* XXX: This is an awful hack that could hurt performance, but on the bright side it should work until we come up with a better solution. The issue is that in the first loop blocksize() is called which calls instrsize() which requires i_oparg be set appropriately. There is a bootstrap problem because i_oparg is calculated in the second loop above. So we loop until we stop seeing new EXTENDED_ARGs. The only EXTENDED_ARGs that could be popping up are ones in jump instructions. So this should converge fairly quickly. */ } while (extended_arg_recompile); } static PyObject * dict_keys_inorder(PyObject *dict, Py_ssize_t offset) { PyObject *tuple, *k, *v; Py_ssize_t i, pos = 0, size = PyDict_Size(dict); tuple = PyTuple_New(size); if (tuple == NULL) return NULL; while (PyDict_Next(dict, &pos, &k, &v)) { i = PyLong_AS_LONG(v); /* The keys of the dictionary are tuples. (see compiler_add_o * and _PyCode_ConstantKey). The object we want is always second, * though. */ k = PyTuple_GET_ITEM(k, 1); Py_INCREF(k); assert((i - offset) < size); assert((i - offset) >= 0); PyTuple_SET_ITEM(tuple, i - offset, k); } return tuple; } static int compute_code_flags(struct compiler *c) { PySTEntryObject *ste = c->u->u_ste; int flags = 0; if (ste->ste_type == FunctionBlock) { flags |= CO_NEWLOCALS | CO_OPTIMIZED; if (ste->ste_nested) flags |= CO_NESTED; if (ste->ste_generator && !ste->ste_coroutine) flags |= CO_GENERATOR; if (!ste->ste_generator && ste->ste_coroutine) flags |= CO_COROUTINE; if (ste->ste_generator && ste->ste_coroutine) flags |= CO_ASYNC_GENERATOR; if (ste->ste_varargs) flags |= CO_VARARGS; if (ste->ste_varkeywords) flags |= CO_VARKEYWORDS; } /* (Only) inherit compilerflags in PyCF_MASK */ flags |= (c->c_flags->cf_flags & PyCF_MASK); return flags; } static PyCodeObject * makecode(struct compiler *c, struct assembler *a) { PyObject *tmp; PyCodeObject *co = NULL; PyObject *consts = NULL; PyObject *names = NULL; PyObject *varnames = NULL; PyObject *name = NULL; PyObject *freevars = NULL; PyObject *cellvars = NULL; PyObject *bytecode = NULL; Py_ssize_t nlocals; int nlocals_int; int flags; int argcount, kwonlyargcount; tmp = dict_keys_inorder(c->u->u_consts, 0); if (!tmp) goto error; consts = PySequence_List(tmp); /* optimize_code requires a list */ Py_DECREF(tmp); names = dict_keys_inorder(c->u->u_names, 0); varnames = dict_keys_inorder(c->u->u_varnames, 0); if (!consts || !names || !varnames) goto error; cellvars = dict_keys_inorder(c->u->u_cellvars, 0); if (!cellvars) goto error; freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars)); if (!freevars) goto error; nlocals = PyDict_Size(c->u->u_varnames); assert(nlocals < INT_MAX); nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int); flags = compute_code_flags(c); if (flags < 0) goto error; bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab); if (!bytecode) goto error; tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */ if (!tmp) goto error; Py_DECREF(consts); consts = tmp; argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int); kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int); co = PyCode_New(argcount, kwonlyargcount, nlocals_int, stackdepth(c), flags, bytecode, consts, names, varnames, freevars, cellvars, c->c_filename, c->u->u_name, c->u->u_firstlineno, a->a_lnotab); error: Py_XDECREF(consts); Py_XDECREF(names); Py_XDECREF(varnames); Py_XDECREF(name); Py_XDECREF(freevars); Py_XDECREF(cellvars); Py_XDECREF(bytecode); return co; } /* For debugging purposes only */ #if 0 static void dump_instr(const struct instr *i) { const char *jrel = i->i_jrel ? "jrel " : ""; const char *jabs = i->i_jabs ? "jabs " : ""; char arg[128]; *arg = '\0'; if (HAS_ARG(i->i_opcode)) { sprintf(arg, "arg: %d ", i->i_oparg); } fprintf(stderr, "line: %d, opcode: %d %s%s%s\n", i->i_lineno, i->i_opcode, arg, jabs, jrel); } static void dump_basicblock(const basicblock *b) { const char *seen = b->b_seen ? "seen " : ""; const char *b_return = b->b_return ? "return " : ""; fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n", b->b_iused, b->b_startdepth, b->b_offset, seen, b_return); if (b->b_instr) { int i; for (i = 0; i < b->b_iused; i++) { fprintf(stderr, " [%02d] ", i); dump_instr(b->b_instr + i); } } } #endif static PyCodeObject * assemble(struct compiler *c, int addNone) { basicblock *b, *entryblock; struct assembler a; int i, j, nblocks; PyCodeObject *co = NULL; /* Make sure every block that falls off the end returns None. XXX NEXT_BLOCK() isn't quite right, because if the last block ends with a jump or return b_next shouldn't set. */ if (!c->u->u_curblock->b_return) { NEXT_BLOCK(c); if (addNone) ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, RETURN_VALUE); } nblocks = 0; entryblock = NULL; for (b = c->u->u_blocks; b != NULL; b = b->b_list) { nblocks++; entryblock = b; } /* Set firstlineno if it wasn't explicitly set. */ if (!c->u->u_firstlineno) { if (entryblock && entryblock->b_instr && entryblock->b_instr->i_lineno) c->u->u_firstlineno = entryblock->b_instr->i_lineno; else c->u->u_firstlineno = 1; } if (!assemble_init(&a, nblocks, c->u->u_firstlineno)) goto error; dfs(c, entryblock, &a); /* Can't modify the bytecode after computing jump offsets. */ assemble_jump_offsets(&a, c); /* Emit code in reverse postorder from dfs. */ for (i = a.a_nblocks - 1; i >= 0; i--) { b = a.a_postorder[i]; for (j = 0; j < b->b_iused; j++) if (!assemble_emit(&a, &b->b_instr[j])) goto error; } if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) goto error; if (_PyBytes_Resize(&a.a_bytecode, a.a_offset * sizeof(_Py_CODEUNIT)) < 0) goto error; co = makecode(c, &a); error: assemble_free(&a); return co; } #undef PyAST_Compile PyCodeObject * PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags, PyArena *arena) { return PyAST_CompileEx(mod, filename, flags, -1, arena); }
157,140
5,388
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/atexit.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" /* clang-format off */ #define NEXITFUNCS 32 static void (*_Py_exitfunc)(void); static void (*exitfuncs[NEXITFUNCS])(void); static int nexitfuncs = 0; void _Py_PyAtExit(void (*func)(void)) { _Py_exitfunc = func; } void _Py_CallExitFuncs(void) { if (!_Py_exitfunc) return; _Py_exitfunc(); PyErr_Clear(); } int Py_AtExit(void (*func)(void)) { if (nexitfuncs >= NEXITFUNCS) return -1; exitfuncs[nexitfuncs++] = func; return 0; } void _Py_CallLlExitFuncs(void) { while (nexitfuncs > 0) (*exitfuncs[--nexitfuncs])(); fflush(stdout); fflush(stderr); }
1,525
47
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/sysmodule.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/dce.h" #include "libc/mem/gc.internal.h" #include "libc/mem/mem.h" #include "libc/nt/dll.h" #include "libc/nt/version.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "libc/str/locale.h" #include "libc/sysv/consts/exit.h" #include "libc/sysv/consts/s.h" #include "libc/x/x.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/eval.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/frameobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/namespaceobject.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/osdefs.h" #include "third_party/python/Include/patchlevel.h" #include "third_party/python/Include/pgenheaders.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pyport.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/pythread.h" #include "third_party/python/Include/structseq.h" #include "third_party/python/Include/traceback.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/warnings.h" #include "third_party/python/Include/yoink.h" #include "third_party/python/pyconfig.h" /* clang-format off */ PYTHON_PROVIDE("sys"); PYTHON_PROVIDE("sys.__displayhook__"); PYTHON_PROVIDE("sys.__doc__"); PYTHON_PROVIDE("sys.__excepthook__"); PYTHON_PROVIDE("sys.__interactivehook__"); PYTHON_PROVIDE("sys.__loader__"); PYTHON_PROVIDE("sys.__name__"); PYTHON_PROVIDE("sys.__package__"); PYTHON_PROVIDE("sys.__spec__"); PYTHON_PROVIDE("sys.__stderr__"); PYTHON_PROVIDE("sys.__stdin__"); PYTHON_PROVIDE("sys.__stdout__"); PYTHON_PROVIDE("sys._clear_type_cache"); PYTHON_PROVIDE("sys._current_frames"); PYTHON_PROVIDE("sys._debugmallocstats"); PYTHON_PROVIDE("sys._getframe"); PYTHON_PROVIDE("sys._git"); PYTHON_PROVIDE("sys._home"); PYTHON_PROVIDE("sys._xoptions"); PYTHON_PROVIDE("sys.abiflags"); PYTHON_PROVIDE("sys.api_version"); PYTHON_PROVIDE("sys.argv"); PYTHON_PROVIDE("sys.base_exec_prefix"); PYTHON_PROVIDE("sys.base_prefix"); PYTHON_PROVIDE("sys.builtin_module_names"); PYTHON_PROVIDE("sys.byteorder"); PYTHON_PROVIDE("sys.call_tracing"); PYTHON_PROVIDE("sys.callstats"); PYTHON_PROVIDE("sys.copyright"); PYTHON_PROVIDE("sys.displayhook"); PYTHON_PROVIDE("sys.dont_write_bytecode"); PYTHON_PROVIDE("sys.exc_info"); PYTHON_PROVIDE("sys.excepthook"); PYTHON_PROVIDE("sys.exec_prefix"); PYTHON_PROVIDE("sys.executable"); PYTHON_PROVIDE("sys.exit"); PYTHON_PROVIDE("sys.flags"); PYTHON_PROVIDE("sys.float_info"); PYTHON_PROVIDE("sys.float_repr_style"); PYTHON_PROVIDE("sys.get_asyncgen_hooks"); PYTHON_PROVIDE("sys.get_coroutine_wrapper"); #if IsModeDbg() PYTHON_PROVIDE("sys.getallocatedblocks"); #endif PYTHON_PROVIDE("sys.getcheckinterval"); PYTHON_PROVIDE("sys.getdefaultencoding"); PYTHON_PROVIDE("sys.getdlopenflags"); PYTHON_PROVIDE("sys.getfilesystemencodeerrors"); PYTHON_PROVIDE("sys.getfilesystemencoding"); PYTHON_PROVIDE("sys.getprofile"); PYTHON_PROVIDE("sys.getrecursionlimit"); PYTHON_PROVIDE("sys.getrefcount"); PYTHON_PROVIDE("sys.getsizeof"); PYTHON_PROVIDE("sys.gettrace"); PYTHON_PROVIDE("sys.hash_info"); PYTHON_PROVIDE("sys.hexversion"); PYTHON_PROVIDE("sys.implementation"); PYTHON_PROVIDE("sys.int_info"); PYTHON_PROVIDE("sys.intern"); PYTHON_PROVIDE("sys.is_finalizing"); PYTHON_PROVIDE("sys.maxsize"); PYTHON_PROVIDE("sys.maxunicode"); PYTHON_PROVIDE("sys.meta_path"); PYTHON_PROVIDE("sys.modules"); PYTHON_PROVIDE("sys.path"); PYTHON_PROVIDE("sys.path_hooks"); PYTHON_PROVIDE("sys.path_importer_cache"); PYTHON_PROVIDE("sys.platform"); PYTHON_PROVIDE("sys.prefix"); PYTHON_PROVIDE("sys.set_asyncgen_hooks"); PYTHON_PROVIDE("sys.set_coroutine_wrapper"); PYTHON_PROVIDE("sys.setcheckinterval"); PYTHON_PROVIDE("sys.setdlopenflags"); PYTHON_PROVIDE("sys.setprofile"); PYTHON_PROVIDE("sys.setrecursionlimit"); PYTHON_PROVIDE("sys.settrace"); PYTHON_PROVIDE("sys.stderr"); PYTHON_PROVIDE("sys.stdin"); PYTHON_PROVIDE("sys.stdout"); PYTHON_PROVIDE("sys.version"); PYTHON_PROVIDE("sys.version_info"); PYTHON_PROVIDE("sys.warnoptions"); _Py_IDENTIFIER(_); _Py_IDENTIFIER(__sizeof__); _Py_IDENTIFIER(buffer); _Py_IDENTIFIER(builtins); _Py_IDENTIFIER(encoding); _Py_IDENTIFIER(path); _Py_IDENTIFIER(stdout); _Py_IDENTIFIER(stderr); _Py_IDENTIFIER(write); PyObject * _PySys_GetObjectId(_Py_Identifier *key) { PyThreadState *tstate = PyThreadState_GET(); PyObject *sd = tstate->interp->sysdict; if (sd == NULL) return NULL; return _PyDict_GetItemId(sd, key); } PyObject * PySys_GetObject(const char *name) { PyThreadState *tstate = PyThreadState_GET(); PyObject *sd = tstate->interp->sysdict; if (sd == NULL) return NULL; return PyDict_GetItemString(sd, name); } int _PySys_SetObjectId(_Py_Identifier *key, PyObject *v) { PyThreadState *tstate = PyThreadState_GET(); PyObject *sd = tstate->interp->sysdict; if (v == NULL) { if (_PyDict_GetItemId(sd, key) == NULL) return 0; else return _PyDict_DelItemId(sd, key); } else return _PyDict_SetItemId(sd, key, v); } int PySys_SetObject(const char *name, PyObject *v) { PyThreadState *tstate = PyThreadState_GET(); PyObject *sd = tstate->interp->sysdict; if (v == NULL) { if (PyDict_GetItemString(sd, name) == NULL) return 0; else return PyDict_DelItemString(sd, name); } else return PyDict_SetItemString(sd, name, v); } /* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace' error handler. If sys.stdout has a buffer attribute, use sys.stdout.buffer.write(encoded), otherwise redecode the string and use sys.stdout.write(redecoded). Helper function for sys_displayhook(). */ static int sys_displayhook_unencodable(PyObject *outf, PyObject *o) { PyObject *stdout_encoding = NULL; PyObject *encoded, *escaped_str, *repr_str, *buffer, *result; char *stdout_encoding_str; int ret; stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding); if (stdout_encoding == NULL) goto error; stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding); if (stdout_encoding_str == NULL) goto error; repr_str = PyObject_Repr(o); if (repr_str == NULL) goto error; encoded = PyUnicode_AsEncodedString(repr_str, stdout_encoding_str, "backslashreplace"); Py_DECREF(repr_str); if (encoded == NULL) goto error; buffer = _PyObject_GetAttrId(outf, &PyId_buffer); if (buffer) { result = _PyObject_CallMethodId(buffer, &PyId_write, "(O)", encoded); Py_DECREF(buffer); Py_DECREF(encoded); if (result == NULL) goto error; Py_DECREF(result); } else { PyErr_Clear(); escaped_str = PyUnicode_FromEncodedObject(encoded, stdout_encoding_str, "strict"); Py_DECREF(encoded); if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) { Py_DECREF(escaped_str); goto error; } Py_DECREF(escaped_str); } ret = 0; goto finally; error: ret = -1; finally: Py_XDECREF(stdout_encoding); return ret; } static PyObject * sys_displayhook(PyObject *self, PyObject *o) { PyObject *outf; PyInterpreterState *interp = PyThreadState_GET()->interp; PyObject *modules = interp->modules; PyObject *builtins; static PyObject *newline = NULL; int err; builtins = _PyDict_GetItemId(modules, &PyId_builtins); if (builtins == NULL) { PyErr_SetString(PyExc_RuntimeError, "lost builtins module"); return NULL; } /* Print value except if None */ /* After printing, also assign to '_' */ /* Before, set '_' to None to avoid recursion */ if (o == Py_None) { Py_INCREF(Py_None); return Py_None; } if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0) return NULL; outf = _PySys_GetObjectId(&PyId_stdout); if (outf == NULL || outf == Py_None) { PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); return NULL; } if (PyFile_WriteObject(o, outf, 0) != 0) { if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) { /* repr(o) is not encodable to sys.stdout.encoding with * sys.stdout.errors error handler (which is probably 'strict') */ PyErr_Clear(); err = sys_displayhook_unencodable(outf, o); if (err) return NULL; } else { return NULL; } } if (newline == NULL) { newline = PyUnicode_FromString("\n"); if (newline == NULL) return NULL; } if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0) return NULL; if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0) return NULL; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(displayhook_doc, "displayhook(object) -> None\n" "\n" "Print an object to sys.stdout and also save it in builtins._\n" ); static PyObject * sys_excepthook(PyObject* self, PyObject* args) { PyObject *exc, *value, *tb; if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb)) return NULL; PyErr_Display(exc, value, tb); Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(excepthook_doc, "excepthook(exctype, value, traceback) -> None\n" "\n" "Handle an exception by displaying it with a traceback on sys.stderr.\n" ); static PyObject * sys_exc_info(PyObject *self, PyObject *noargs) { PyThreadState *tstate; tstate = PyThreadState_GET(); return Py_BuildValue( "(OOO)", tstate->exc_type != NULL ? tstate->exc_type : Py_None, tstate->exc_value != NULL ? tstate->exc_value : Py_None, tstate->exc_traceback != NULL ? tstate->exc_traceback : Py_None); } PyDoc_STRVAR(exc_info_doc, "exc_info() -> (type, value, traceback)\n\ \n\ Return information about the most recent exception caught by an except\n\ clause in the current stack frame or in an older stack frame." ); static PyObject * sys_exit(PyObject *self, PyObject *args) { PyObject *exit_code = 0; if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) return NULL; /* Raise SystemExit so callers may catch it or clean up. */ PyErr_SetObject(PyExc_SystemExit, exit_code); return NULL; } PyDoc_STRVAR(exit_doc, "exit([status])\n\ \n\ Exit the interpreter by raising SystemExit(status).\n\ If the status is omitted or None, it defaults to zero (i.e., success).\n\ If the status is an integer, it will be used as the system exit status.\n\ If it is another kind of object, it will be printed and the system\n\ exit status will be one (i.e., failure)." ); static PyObject * sys_getdefaultencoding(PyObject *self) { return PyUnicode_FromString(PyUnicode_GetDefaultEncoding()); } PyDoc_STRVAR(getdefaultencoding_doc, "getdefaultencoding() -> string\n\ \n\ Return the current default string encoding used by the Unicode \n\ implementation." ); static PyObject * sys_getfilesystemencoding(PyObject *self) { if (Py_FileSystemDefaultEncoding) return PyUnicode_FromString(Py_FileSystemDefaultEncoding); PyErr_SetString(PyExc_RuntimeError, "filesystem encoding is not initialized"); return NULL; } PyDoc_STRVAR(getfilesystemencoding_doc, "getfilesystemencoding() -> string\n\ \n\ Return the encoding used to convert Unicode filenames in\n\ operating system filenames." ); static PyObject * sys_getfilesystemencodeerrors(PyObject *self) { if (Py_FileSystemDefaultEncodeErrors) return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors); PyErr_SetString(PyExc_RuntimeError, "filesystem encoding is not initialized"); return NULL; } PyDoc_STRVAR(getfilesystemencodeerrors_doc, "getfilesystemencodeerrors() -> string\n\ \n\ Return the error mode used to convert Unicode filenames in\n\ operating system filenames." ); static PyObject * sys_intern(PyObject *self, PyObject *args) { PyObject *s; if (!PyArg_ParseTuple(args, "U:intern", &s)) return NULL; if (PyUnicode_CheckExact(s)) { Py_INCREF(s); PyUnicode_InternInPlace(&s); return s; } else { PyErr_Format(PyExc_TypeError, "can't intern %.400s", s->ob_type->tp_name); return NULL; } } PyDoc_STRVAR(intern_doc, "intern(string) -> string\n\ \n\ ``Intern'' the given string. This enters the string in the (global)\n\ table of interned strings whose purpose is to speed up dictionary lookups.\n\ Return the string itself or the previously interned string object with the\n\ same value."); /* * Cached interned string objects used for calling the profile and * trace functions. Initialized by trace_init(). */ static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL}; static int trace_init(void) { static const char * const whatnames[7] = { "call", "exception", "line", "return", "c_call", "c_exception", "c_return" }; PyObject *name; int i; for (i = 0; i < 7; ++i) { if (whatstrings[i] == NULL) { name = PyUnicode_InternFromString(whatnames[i]); if (name == NULL) return -1; whatstrings[i] = name; } } return 0; } static PyObject * call_trampoline(PyObject* callback, PyFrameObject *frame, int what, PyObject *arg) { PyObject *result; PyObject *stack[3]; if (PyFrame_FastToLocalsWithError(frame) < 0) { return NULL; } stack[0] = (PyObject *)frame; stack[1] = whatstrings[what]; stack[2] = (arg != NULL) ? arg : Py_None; /* call the Python-level function */ result = _PyObject_FastCall(callback, stack, 3); PyFrame_LocalsToFast(frame, 1); if (result == NULL) { PyTraceBack_Here(frame); } return result; } static int profile_trampoline(PyObject *self, PyFrameObject *frame, int what, PyObject *arg) { PyObject *result; if (arg == NULL) arg = Py_None; result = call_trampoline(self, frame, what, arg); if (result == NULL) { PyEval_SetProfile(NULL, NULL); return -1; } Py_DECREF(result); return 0; } static int trace_trampoline(PyObject *self, PyFrameObject *frame, int what, PyObject *arg) { PyObject *callback; PyObject *result; if (what == PyTrace_CALL) callback = self; else callback = frame->f_trace; if (callback == NULL) return 0; result = call_trampoline(callback, frame, what, arg); if (result == NULL) { PyEval_SetTrace(NULL, NULL); Py_CLEAR(frame->f_trace); return -1; } if (result != Py_None) { Py_XSETREF(frame->f_trace, result); } else { Py_DECREF(result); } return 0; } static PyObject * sys_settrace(PyObject *self, PyObject *args) { if (trace_init() == -1) return NULL; if (args == Py_None) PyEval_SetTrace(NULL, NULL); else PyEval_SetTrace(trace_trampoline, args); Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(settrace_doc, "settrace(function)\n\ \n\ Set the global debug tracing function. It will be called on each\n\ function call. See the debugger chapter in the library manual." ); static PyObject * sys_gettrace(PyObject *self, PyObject *args) { PyThreadState *tstate = PyThreadState_GET(); PyObject *temp = tstate->c_traceobj; if (temp == NULL) temp = Py_None; Py_INCREF(temp); return temp; } PyDoc_STRVAR(gettrace_doc, "gettrace()\n\ \n\ Return the global debug tracing function set with sys.settrace.\n\ See the debugger chapter in the library manual." ); static PyObject * sys_setprofile(PyObject *self, PyObject *args) { if (trace_init() == -1) return NULL; if (args == Py_None) PyEval_SetProfile(NULL, NULL); else PyEval_SetProfile(profile_trampoline, args); Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(setprofile_doc, "setprofile(function)\n\ \n\ Set the profiling function. It will be called on each function call\n\ and return. See the profiler chapter in the library manual." ); static PyObject * sys_getprofile(PyObject *self, PyObject *args) { PyThreadState *tstate = PyThreadState_GET(); PyObject *temp = tstate->c_profileobj; if (temp == NULL) temp = Py_None; Py_INCREF(temp); return temp; } PyDoc_STRVAR(getprofile_doc, "getprofile()\n\ \n\ Return the profiling function set with sys.setprofile.\n\ See the profiler chapter in the library manual." ); static int _check_interval = 100; static PyObject * sys_setcheckinterval(PyObject *self, PyObject *args) { if (PyErr_WarnEx(PyExc_DeprecationWarning, "sys.getcheckinterval() and sys.setcheckinterval() " "are deprecated. Use sys.setswitchinterval() " "instead.", 1) < 0) return NULL; if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval)) return NULL; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(setcheckinterval_doc, "setcheckinterval(n)\n\ \n\ Tell the Python interpreter to check for asynchronous events every\n\ n instructions. This also affects how often thread switches occur." ); static PyObject * sys_getcheckinterval(PyObject *self, PyObject *args) { if (PyErr_WarnEx(PyExc_DeprecationWarning, "sys.getcheckinterval() and sys.setcheckinterval() " "are deprecated. Use sys.getswitchinterval() " "instead.", 1) < 0) return NULL; return PyLong_FromLong(_check_interval); } PyDoc_STRVAR(getcheckinterval_doc, "getcheckinterval() -> current check interval; see setcheckinterval()." ); #ifdef WITH_THREAD static PyObject * sys_setswitchinterval(PyObject *self, PyObject *args) { double d; if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d)) return NULL; if (d <= 0.0) { PyErr_SetString(PyExc_ValueError, "switch interval must be strictly positive"); return NULL; } _PyEval_SetSwitchInterval((unsigned long) (1e6 * d)); Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(setswitchinterval_doc, "setswitchinterval(n)\n\ \n\ Set the ideal thread switching delay inside the Python interpreter\n\ The actual frequency of switching threads can be lower if the\n\ interpreter executes long sequences of uninterruptible code\n\ (this is implementation-specific and workload-dependent).\n\ \n\ The parameter must represent the desired switching delay in seconds\n\ A typical value is 0.005 (5 milliseconds)." ); static PyObject * sys_getswitchinterval(PyObject *self, PyObject *args) { return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval()); } PyDoc_STRVAR(getswitchinterval_doc, "getswitchinterval() -> current thread switch interval; see setswitchinterval()." ); #endif /* WITH_THREAD */ static PyObject * sys_setrecursionlimit(PyObject *self, PyObject *args) { int new_limit, mark; PyThreadState *tstate; if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit)) return NULL; if (new_limit < 1) { PyErr_SetString(PyExc_ValueError, "recursion limit must be greater or equal than 1"); return NULL; } /* Issue #25274: When the recursion depth hits the recursion limit in _Py_CheckRecursiveCall(), the overflowed flag of the thread state is set to 1 and a RecursionError is raised. The overflowed flag is reset to 0 when the recursion depth goes below the low-water mark: see Py_LeaveRecursiveCall(). Reject too low new limit if the current recursion depth is higher than the new low-water mark. Otherwise it may not be possible anymore to reset the overflowed flag to 0. */ mark = _Py_RecursionLimitLowerWaterMark(new_limit); tstate = PyThreadState_GET(); if (tstate->recursion_depth >= mark) { PyErr_Format(PyExc_RecursionError, "cannot set the recursion limit to %i at " "the recursion depth %i: the limit is too low", new_limit, tstate->recursion_depth); return NULL; } Py_SetRecursionLimit(new_limit); Py_INCREF(Py_None); return Py_None; } static PyObject * sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper) { if (wrapper != Py_None) { if (!PyCallable_Check(wrapper)) { PyErr_Format(PyExc_TypeError, "callable expected, got %.50s", Py_TYPE(wrapper)->tp_name); return NULL; } _PyEval_SetCoroutineWrapper(wrapper); } else { _PyEval_SetCoroutineWrapper(NULL); } Py_RETURN_NONE; } PyDoc_STRVAR(set_coroutine_wrapper_doc, "set_coroutine_wrapper(wrapper)\n\ \n\ Set a wrapper for coroutine objects." ); static PyObject * sys_get_coroutine_wrapper(PyObject *self, PyObject *args) { PyObject *wrapper = _PyEval_GetCoroutineWrapper(); if (wrapper == NULL) { wrapper = Py_None; } Py_INCREF(wrapper); return wrapper; } PyDoc_STRVAR(get_coroutine_wrapper_doc, "get_coroutine_wrapper()\n\ \n\ Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper." ); static PyTypeObject AsyncGenHooksType; PyDoc_STRVAR(asyncgen_hooks_doc, "asyncgen_hooks\n\ \n\ A struct sequence providing information about asynhronous\n\ generators hooks. The attributes are read only."); static PyStructSequence_Field asyncgen_hooks_fields[] = { {"firstiter", PyDoc_STR("Hook to intercept first iteration")}, {"finalizer", PyDoc_STR("Hook to intercept finalization")}, {0} }; static PyStructSequence_Desc asyncgen_hooks_desc = { "asyncgen_hooks", /* name */ asyncgen_hooks_doc, /* doc */ asyncgen_hooks_fields , /* fields */ 2 }; static PyObject * sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw) { static char *keywords[] = {"firstiter", "finalizer", NULL}; PyObject *firstiter = NULL; PyObject *finalizer = NULL; if (!PyArg_ParseTupleAndKeywords( args, kw, "|OO", keywords, &firstiter, &finalizer)) { return NULL; } if (finalizer && finalizer != Py_None) { if (!PyCallable_Check(finalizer)) { PyErr_Format(PyExc_TypeError, "callable finalizer expected, got %.50s", Py_TYPE(finalizer)->tp_name); return NULL; } _PyEval_SetAsyncGenFinalizer(finalizer); } else if (finalizer == Py_None) { _PyEval_SetAsyncGenFinalizer(NULL); } if (firstiter && firstiter != Py_None) { if (!PyCallable_Check(firstiter)) { PyErr_Format(PyExc_TypeError, "callable firstiter expected, got %.50s", Py_TYPE(firstiter)->tp_name); return NULL; } _PyEval_SetAsyncGenFirstiter(firstiter); } else if (firstiter == Py_None) { _PyEval_SetAsyncGenFirstiter(NULL); } Py_RETURN_NONE; } PyDoc_STRVAR(set_asyncgen_hooks_doc, "set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\ \n\ Set a finalizer for async generators objects." ); static PyObject * sys_get_asyncgen_hooks(PyObject *self, PyObject *args) { PyObject *res; PyObject *firstiter = _PyEval_GetAsyncGenFirstiter(); PyObject *finalizer = _PyEval_GetAsyncGenFinalizer(); res = PyStructSequence_New(&AsyncGenHooksType); if (res == NULL) { return NULL; } if (firstiter == NULL) { firstiter = Py_None; } if (finalizer == NULL) { finalizer = Py_None; } Py_INCREF(firstiter); PyStructSequence_SET_ITEM(res, 0, firstiter); Py_INCREF(finalizer); PyStructSequence_SET_ITEM(res, 1, finalizer); return res; } PyDoc_STRVAR(get_asyncgen_hooks_doc, "get_asyncgen_hooks()\n\ \n\ Return a namedtuple of installed asynchronous generators hooks \ (firstiter, finalizer)." ); static PyTypeObject Hash_InfoType; PyDoc_STRVAR(hash_info_doc, "hash_info\n\ \n\ A struct sequence providing parameters used for computing\n\ hashes. The attributes are read only."); static PyStructSequence_Field hash_info_fields[] = { {"width", PyDoc_STR("width of the type used for hashing, in bits")}, {"modulus", PyDoc_STR("prime number giving the modulus on which the hash function is based")}, {"inf", PyDoc_STR("value to be used for hash of a positive infinity")}, {"nan", PyDoc_STR("value to be used for hash of a nan")}, {"imag", PyDoc_STR("multiplier used for the imaginary part of a complex number")}, {"algorithm", PyDoc_STR("name of the algorithm for hashing of str, bytes and memoryviews")}, {"hash_bits", PyDoc_STR("internal output size of hash algorithm")}, {"seed_bits", PyDoc_STR("seed size of hash algorithm")}, {"cutoff", PyDoc_STR("small string optimization cutoff")}, {NULL, NULL} }; static PyStructSequence_Desc hash_info_desc = { "sys.hash_info", hash_info_doc, hash_info_fields, 9, }; static PyObject * get_hash_info(void) { PyObject *hash_info; int field = 0; PyHash_FuncDef *hashfunc; hash_info = PyStructSequence_New(&Hash_InfoType); if (hash_info == NULL) return NULL; hashfunc = PyHash_GetFuncDef(); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(8*sizeof(Py_hash_t))); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromSsize_t(_PyHASH_MODULUS)); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(_PyHASH_INF)); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(_PyHASH_NAN)); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(_PyHASH_IMAG)); PyStructSequence_SET_ITEM(hash_info, field++, PyUnicode_FromString(hashfunc->name)); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(hashfunc->hash_bits)); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(hashfunc->seed_bits)); PyStructSequence_SET_ITEM(hash_info, field++, PyLong_FromLong(Py_HASH_CUTOFF)); if (PyErr_Occurred()) { Py_CLEAR(hash_info); return NULL; } return hash_info; } PyDoc_STRVAR(setrecursionlimit_doc, "setrecursionlimit(n)\n\ \n\ Set the maximum depth of the Python interpreter stack to n. This\n\ limit prevents infinite recursion from causing an overflow of the C\n\ stack and crashing Python. The highest possible limit is platform-\n\ dependent." ); static PyObject * sys_getrecursionlimit(PyObject *self) { return PyLong_FromLong(Py_GetRecursionLimit()); } PyDoc_STRVAR(getrecursionlimit_doc, "getrecursionlimit()\n\ \n\ Return the current value of the recursion limit, the maximum depth\n\ of the Python interpreter stack. This limit prevents infinite\n\ recursion from causing an overflow of the C stack and crashing Python." ); PyDoc_STRVAR(getwindowsversion_doc, "getwindowsversion()\n\ \n\ Return information about the running version of Windows as a named tuple.\n\ The members are named: major, minor, build, platform, service_pack,\n\ service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\ backward compatibility, only the first 5 items are available by indexing.\n\ All elements are numbers, except service_pack and platform_type which are\n\ strings, and platform_version which is a 3-tuple. Platform is always 2.\n\ Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\ server. Platform_version is a 3-tuple containing a version number that is\n\ intended for identifying the OS rather than feature detection." ); static PyTypeObject WindowsVersionType = {0}; static PyStructSequence_Field windows_version_fields[] = { {"major", PyDoc_STR("Major version number")}, {"minor", PyDoc_STR("Minor version number")}, {"build", PyDoc_STR("Build number")}, {"platform", PyDoc_STR("Operating system platform")}, {"service_pack", PyDoc_STR("Latest Service Pack installed on the system")}, {"service_pack_major", PyDoc_STR("Service Pack major version number")}, {"service_pack_minor", PyDoc_STR("Service Pack minor version number")}, {"suite_mask", PyDoc_STR("Bit mask identifying available product suites")}, {"product_type", PyDoc_STR("System product type")}, {"platform_version", PyDoc_STR("Diagnostic version number")}, {0} }; static PyStructSequence_Desc windows_version_desc = { "sys.getwindowsversion", /* name */ getwindowsversion_doc, /* doc */ windows_version_fields, /* fields */ 5 /* For backward compatibility, only the first 5 items are accessible via indexing, the rest are name only */ }; static PyObject * sys_getwindowsversion(PyObject *self) { int pos = 0; PyObject *version; struct NtOsVersionInfo ver; uint32_t realMajor, realMinor, realBuild; int64_t hKernel32; wchar_t kernel32_path[PATH_MAX]; void *verblock; uint32_t verblock_size; ver.dwOSVersionInfoSize = sizeof(ver); if (!GetVersionEx(&ver)) return PyErr_SetFromWindowsErr(0); version = PyStructSequence_New(&WindowsVersionType); if (version == NULL) return NULL; PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId)); PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(gc(utf16to8(ver.szCSDVersion,-1,0)))); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask)); PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType)); realMajor = ver.dwMajorVersion; realMinor = ver.dwMinorVersion; realBuild = ver.dwBuildNumber; #if 0 // todo(jart): port me // GetVersion will lie if we are running in a compatibility mode. // We need to read the version info from a system file resource // to accurately identify the OS version. If we fail for any reason, // just return whatever GetVersion said. hKernel32 = GetModuleHandle("kernel32.dll"); if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) && (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) && (verblock = PyMem_RawMalloc(verblock_size))) { VS_FIXEDFILEINFO *ffi; UINT ffi_len; if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) && VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) { realMajor = HIWORD(ffi->dwProductVersionMS); realMinor = LOWORD(ffi->dwProductVersionMS); realBuild = HIWORD(ffi->dwProductVersionLS); } PyMem_RawFree(verblock); } PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)", realMajor, realMinor, realBuild )); #endif if (PyErr_Occurred()) { Py_DECREF(version); return NULL; } return version; } #ifdef MS_WINDOWS #pragma warning(pop) PyDoc_STRVAR(enablelegacywindowsfsencoding_doc, "_enablelegacywindowsfsencoding()\n\ \n\ Changes the default filesystem encoding to mbcs:replace for consistency\n\ with earlier versions of Python. See PEP 529 for more information.\n\ \n\ This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\ environment variable before launching Python." ); static PyObject * sys_enablelegacywindowsfsencoding(PyObject *self) { Py_FileSystemDefaultEncoding = "mbcs"; Py_FileSystemDefaultEncodeErrors = "replace"; Py_RETURN_NONE; } #endif /* MS_WINDOWS */ #ifdef HAVE_DLOPEN static PyObject * sys_setdlopenflags(PyObject *self, PyObject *args) { int new_val; PyThreadState *tstate = PyThreadState_GET(); if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val)) return NULL; if (!tstate) return NULL; tstate->interp->dlopenflags = new_val; Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR(setdlopenflags_doc, "setdlopenflags(n) -> None\n\ \n\ Set the flags used by the interpreter for dlopen calls, such as when the\n\ interpreter loads extension modules. Among other things, this will enable\n\ a lazy resolving of symbols when importing a module, if called as\n\ sys.setdlopenflags(0). To share symbols across extension modules, call as\n\ sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\ can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY)."); static PyObject * sys_getdlopenflags(PyObject *self, PyObject *args) { PyThreadState *tstate = PyThreadState_GET(); if (!tstate) return NULL; return PyLong_FromLong(tstate->interp->dlopenflags); } PyDoc_STRVAR(getdlopenflags_doc, "getdlopenflags() -> int\n\ \n\ Return the current value of the flags that are used for dlopen calls.\n\ The flag constants are defined in the os module."); #endif /* HAVE_DLOPEN */ #ifdef USE_MALLOPT /* Link with -lmalloc (or -lmpc) on an SGI */ static PyObject * sys_mdebug(PyObject *self, PyObject *args) { int flag; if (!PyArg_ParseTuple(args, "i:mdebug", &flag)) return NULL; mallopt(M_DEBUG, flag); Py_INCREF(Py_None); return Py_None; } #endif /* USE_MALLOPT */ size_t _PySys_GetSizeOf(PyObject *o) { PyObject *res = NULL; PyObject *method; Py_ssize_t size; /* Make sure the type is initialized. float gets initialized late */ if (PyType_Ready(Py_TYPE(o)) < 0) return (size_t)-1; method = _PyObject_LookupSpecial(o, &PyId___sizeof__); if (method == NULL) { if (!PyErr_Occurred()) PyErr_Format(PyExc_TypeError, "Type %.100s doesn't define __sizeof__", Py_TYPE(o)->tp_name); } else { res = PyObject_CallFunctionObjArgs(method, NULL); Py_DECREF(method); } if (res == NULL) return (size_t)-1; size = PyLong_AsSsize_t(res); Py_DECREF(res); if (size == -1 && PyErr_Occurred()) return (size_t)-1; if (size < 0) { PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0"); return (size_t)-1; } /* add gc_head size */ if (PyObject_IS_GC(o)) return ((size_t)size) + sizeof(PyGC_Head); return (size_t)size; } static PyObject * sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"object", "default", 0}; size_t size; PyObject *o, *dflt = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof", kwlist, &o, &dflt)) return NULL; size = _PySys_GetSizeOf(o); if (size == (size_t)-1 && PyErr_Occurred()) { /* Has a default value been given */ if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) { PyErr_Clear(); Py_INCREF(dflt); return dflt; } else return NULL; } return PyLong_FromSize_t(size); } PyDoc_STRVAR(getsizeof_doc, "getsizeof(object, default) -> int\n\ \n\ Return the size of object in bytes."); static PyObject * sys_getrefcount(PyObject *self, PyObject *arg) { return PyLong_FromSsize_t(arg->ob_refcnt); } #ifdef Py_REF_DEBUG static PyObject * sys_gettotalrefcount(PyObject *self) { return PyLong_FromSsize_t(_Py_GetRefTotal()); } #endif /* Py_REF_DEBUG */ PyDoc_STRVAR(getrefcount_doc, "getrefcount(object) -> integer\n\ \n\ Return the reference count of object. The count returned is generally\n\ one higher than you might expect, because it includes the (temporary)\n\ reference as an argument to getrefcount()." ); #if IsModeDbg() static PyObject * sys_getallocatedblocks(PyObject *self) { return PyLong_FromSsize_t(_Py_GetAllocatedBlocks()); } PyDoc_STRVAR(getallocatedblocks_doc, "getallocatedblocks() -> integer\n\ \n\ Return the number of memory blocks currently allocated, regardless of their\n\ size." ); #endif #ifdef COUNT_ALLOCS static PyObject * sys_getcounts(PyObject *self) { extern PyObject *get_counts(void); return get_counts(); } #endif PyDoc_STRVAR(getframe_doc, "_getframe([depth]) -> frameobject\n\ \n\ Return a frame object from the call stack. If optional integer depth is\n\ given, return the frame object that many calls below the top of the stack.\n\ If that is deeper than the call stack, ValueError is raised. The default\n\ for depth is zero, returning the frame at the top of the call stack.\n\ \n\ This function should be used for internal and specialized\n\ purposes only." ); static PyObject * sys_getframe(PyObject *self, PyObject *args) { PyFrameObject *f = PyThreadState_GET()->frame; int depth = -1; if (!PyArg_ParseTuple(args, "|i:_getframe", &depth)) return NULL; while (depth > 0 && f != NULL) { f = f->f_back; --depth; } if (f == NULL) { PyErr_SetString(PyExc_ValueError, "call stack is not deep enough"); return NULL; } Py_INCREF(f); return (PyObject*)f; } PyDoc_STRVAR(current_frames_doc, "_current_frames() -> dictionary\n\ \n\ Return a dictionary mapping each current thread T's thread id to T's\n\ current stack frame.\n\ \n\ This function should be used for specialized purposes only." ); static PyObject * sys_current_frames(PyObject *self, PyObject *noargs) { return _PyThread_CurrentFrames(); } PyDoc_STRVAR(call_tracing_doc, "call_tracing(func, args) -> object\n\ \n\ Call func(*args), while tracing is enabled. The tracing state is\n\ saved, and restored afterwards. This is intended to be called from\n\ a debugger from a checkpoint, to recursively debug some other code." ); static PyObject * sys_call_tracing(PyObject *self, PyObject *args) { PyObject *func, *funcargs; if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs)) return NULL; return _PyEval_CallTracing(func, funcargs); } PyDoc_STRVAR(callstats_doc, "callstats() -> tuple of integers\n\ \n\ Return a tuple of function call statistics, if CALL_PROFILE was defined\n\ when Python was built. Otherwise, return None.\n\ \n\ When enabled, this function returns detailed, implementation-specific\n\ details about the number of function calls executed. The return value is\n\ a 11-tuple where the entries in the tuple are counts of:\n\ 0. all function calls\n\ 1. calls to PyFunction_Type objects\n\ 2. PyFunction calls that do not create an argument tuple\n\ 3. PyFunction calls that do not create an argument tuple\n\ and bypass PyEval_EvalCodeEx()\n\ 4. PyMethod calls\n\ 5. PyMethod calls on bound methods\n\ 6. PyType calls\n\ 7. PyCFunction calls\n\ 8. generator calls\n\ 9. All other calls\n\ 10. Number of stack pops performed by call_function()" ); #ifdef __cplusplus extern "C" { #endif static PyObject * sys_debugmallocstats(PyObject *self, PyObject *args) { #ifdef WITH_PYMALLOC #if IsModeDbg() if (_PyMem_PymallocEnabled()) { _PyObject_DebugMallocStats(stderr); fputc('\n', stderr); } #endif #endif _PyObject_DebugTypeStats(stderr); Py_RETURN_NONE; } PyDoc_STRVAR(debugmallocstats_doc, "_debugmallocstats()\n\ \n\ Print summary info to stderr about the state of\n\ pymalloc's structures.\n\ \n\ In Py_DEBUG mode, also perform some expensive internal consistency\n\ checks.\n\ "); #ifdef Py_TRACE_REFS /* Defined in objects.c because it uses static globals if that file */ extern PyObject *_Py_GetObjects(PyObject *, PyObject *); #endif #ifdef DYNAMIC_EXECUTION_PROFILE /* Defined in ceval.c because it uses static globals if that file */ extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *); #endif #ifdef __cplusplus } #endif static PyObject * sys_clear_type_cache(PyObject* self, PyObject* args) { PyType_ClearCache(); Py_RETURN_NONE; } PyDoc_STRVAR(sys_clear_type_cache__doc__, "_clear_type_cache() -> None\n\ Clear the internal type lookup cache."); static PyObject * sys_is_finalizing(PyObject* self, PyObject* args) { return PyBool_FromLong(_Py_Finalizing != NULL); } PyDoc_STRVAR(is_finalizing_doc, "is_finalizing()\n\ Return True if Python is exiting."); static PyMethodDef sys_methods[] = { /* Might as well keep this in alphabetic order */ {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS, callstats_doc}, {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, sys_clear_type_cache__doc__}, {"_current_frames", sys_current_frames, METH_NOARGS, current_frames_doc}, {"displayhook", sys_displayhook, METH_O, displayhook_doc}, {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc}, {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc}, {"exit", sys_exit, METH_VARARGS, exit_doc}, {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, METH_NOARGS, getdefaultencoding_doc}, #ifdef HAVE_DLOPEN {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS, getdlopenflags_doc}, #endif #if IsModeDbg() {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS, getallocatedblocks_doc}, #endif #ifdef COUNT_ALLOCS {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS}, #endif #ifdef DYNAMIC_EXECUTION_PROFILE {"getdxp", _Py_GetDXProfile, METH_VARARGS}, #endif {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding, METH_NOARGS, getfilesystemencoding_doc}, { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors, METH_NOARGS, getfilesystemencodeerrors_doc }, #ifdef Py_TRACE_REFS {"getobjects", _Py_GetObjects, METH_VARARGS}, #endif #ifdef Py_REF_DEBUG {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS}, #endif {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc}, {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS, getrecursionlimit_doc}, {"getsizeof", (PyCFunction)sys_getsizeof, METH_VARARGS | METH_KEYWORDS, getsizeof_doc}, {"_getframe", sys_getframe, METH_VARARGS, getframe_doc}, {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS, getwindowsversion_doc}, #ifdef MS_WINDOWS {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding, METH_NOARGS, enablelegacywindowsfsencoding_doc }, #endif /* MS_WINDOWS */ {"intern", sys_intern, METH_VARARGS, intern_doc}, {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc}, #ifdef USE_MALLOPT {"mdebug", sys_mdebug, METH_VARARGS}, #endif {"setcheckinterval", sys_setcheckinterval, METH_VARARGS, setcheckinterval_doc}, {"getcheckinterval", sys_getcheckinterval, METH_NOARGS, getcheckinterval_doc}, #ifdef WITH_THREAD {"setswitchinterval", sys_setswitchinterval, METH_VARARGS, setswitchinterval_doc}, {"getswitchinterval", sys_getswitchinterval, METH_NOARGS, getswitchinterval_doc}, #endif #ifdef HAVE_DLOPEN {"setdlopenflags", sys_setdlopenflags, METH_VARARGS, setdlopenflags_doc}, #endif {"setprofile", sys_setprofile, METH_O, setprofile_doc}, {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc}, {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS, setrecursionlimit_doc}, {"settrace", sys_settrace, METH_O, settrace_doc}, {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc}, {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc}, {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS, debugmallocstats_doc}, {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O, set_coroutine_wrapper_doc}, {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS, get_coroutine_wrapper_doc}, {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks, METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc}, {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS, get_asyncgen_hooks_doc}, {NULL, NULL} /* sentinel */ }; static PyObject * list_builtin_module_names(void) { PyObject *list = PyList_New(0); int i; if (list == NULL) return NULL; for (i = 0; PyImport_Inittab[i].name != NULL; i++) { PyObject *name = PyUnicode_FromString( PyImport_Inittab[i].name); if (name == NULL) break; PyList_Append(list, name); Py_DECREF(name); } if (PyList_Sort(list) != 0) { Py_DECREF(list); list = NULL; } if (list) { PyObject *v = PyList_AsTuple(list); Py_DECREF(list); list = v; } return list; } static PyObject *warnoptions = NULL; void PySys_ResetWarnOptions(void) { if (warnoptions == NULL || !PyList_Check(warnoptions)) return; PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL); } void PySys_AddWarnOptionUnicode(PyObject *unicode) { if (warnoptions == NULL || !PyList_Check(warnoptions)) { Py_XDECREF(warnoptions); warnoptions = PyList_New(0); if (warnoptions == NULL) return; } PyList_Append(warnoptions, unicode); } void PySys_AddWarnOption(const wchar_t *s) { PyObject *unicode; unicode = PyUnicode_FromWideChar(s, -1); if (unicode == NULL) return; PySys_AddWarnOptionUnicode(unicode); Py_DECREF(unicode); } int PySys_HasWarnOptions(void) { return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0; } static PyObject *xoptions = NULL; static PyObject * get_xoptions(void) { if (xoptions == NULL || !PyDict_Check(xoptions)) { Py_XDECREF(xoptions); xoptions = PyDict_New(); } return xoptions; } void PySys_AddXOption(const wchar_t *s) { PyObject *opts; PyObject *name = NULL, *value = NULL; const wchar_t *name_end; opts = get_xoptions(); if (opts == NULL) goto error; name_end = wcschr(s, L'='); if (!name_end) { name = PyUnicode_FromWideChar(s, -1); value = Py_True; Py_INCREF(value); } else { name = PyUnicode_FromWideChar(s, name_end - s); value = PyUnicode_FromWideChar(name_end + 1, -1); } if (name == NULL || value == NULL) goto error; PyDict_SetItem(opts, name, value); Py_DECREF(name); Py_DECREF(value); return; error: Py_XDECREF(name); Py_XDECREF(value); /* No return value, therefore clear error state if possible */ if (_PyThreadState_UncheckedGet()) PyErr_Clear(); } PyObject * PySys_GetXOptions(void) { return get_xoptions(); } /* XXX This doc string is too long to be a single string literal in VC++ 5.0. Two literals concatenated works just fine. If you have a K&R compiler or other abomination that however *does* understand longer strings, get rid of the !!! comment in the middle and the quotes that surround it. */ PyDoc_VAR(sys_doc) = PyDoc_STR( "This module provides access to some objects used or maintained by the\n\ interpreter and to functions that interact strongly with the interpreter.\n\ \n\ Dynamic objects:\n\ \n\ argv -- command line arguments; argv[0] is the script pathname if known\n\ path -- module search path; path[0] is the script directory, else ''\n\ modules -- dictionary of loaded modules\n\ \n\ displayhook -- called to show results in an interactive session\n\ excepthook -- called to handle any uncaught exception other than SystemExit\n\ To customize printing in an interactive session or to install a custom\n\ top-level exception handler, assign other functions to replace these.\n\ \n\ stdin -- standard input file object; used by input()\n\ stdout -- standard output file object; used by print()\n\ stderr -- standard error object; used for error messages\n\ By assigning other file objects (or objects that behave like files)\n\ to these, it is possible to redirect all of the interpreter's I/O.\n\ \n\ last_type -- type of last uncaught exception\n\ last_value -- value of last uncaught exception\n\ last_traceback -- traceback of last uncaught exception\n\ These three are only available in an interactive session after a\n\ traceback has been printed.\n\ " ) /* concatenating string here */ PyDoc_STR( "\n\ Static objects:\n\ \n\ builtin_module_names -- tuple of module names built into this interpreter\n\ copyright -- copyright notice pertaining to this interpreter\n\ exec_prefix -- prefix used to find the machine-specific Python library\n\ executable -- absolute path of the executable binary of the Python interpreter\n\ float_info -- a struct sequence with information about the float implementation.\n\ float_repr_style -- string indicating the style of repr() output for floats\n\ hash_info -- a struct sequence with information about the hash algorithm.\n\ hexversion -- version information encoded as a single integer\n\ implementation -- Python implementation information.\n\ int_info -- a struct sequence with information about the int implementation.\n\ maxsize -- the largest supported length of containers.\n\ maxunicode -- the value of the largest Unicode code point\n\ platform -- platform identifier\n\ prefix -- prefix used to find the Python library\n\ thread_info -- a struct sequence with information about the thread implementation.\n\ version -- the version of this interpreter as a string\n\ version_info -- version information as a named tuple\n\ " ) #ifdef MS_COREDLL /* concatenating string here */ PyDoc_STR( "dllhandle -- [Windows only] integer handle of the Python DLL\n\ winver -- [Windows only] version number of the Python DLL\n\ " ) #endif /* MS_COREDLL */ #ifdef MS_WINDOWS /* concatenating string here */ PyDoc_STR( "_enablelegacywindowsfsencoding -- [Windows only] \n\ " ) #endif PyDoc_STR( "__stdin__ -- the original stdin; don't touch!\n\ __stdout__ -- the original stdout; don't touch!\n\ __stderr__ -- the original stderr; don't touch!\n\ __displayhook__ -- the original displayhook; don't touch!\n\ __excepthook__ -- the original excepthook; don't touch!\n\ \n\ Functions:\n\ \n\ displayhook() -- print an object to the screen, and save it in builtins._\n\ excepthook() -- print an exception and its traceback to sys.stderr\n\ exc_info() -- return thread-safe information about the current exception\n\ exit() -- exit the interpreter by raising SystemExit\n\ getdlopenflags() -- returns flags to be used for dlopen() calls\n\ getprofile() -- get the global profiling function\n\ getrefcount() -- return the reference count for an object (plus one :-)\n\ getrecursionlimit() -- return the max recursion depth for the interpreter\n\ getsizeof() -- return the size of an object in bytes\n\ gettrace() -- get the global debug tracing function\n\ setcheckinterval() -- control how often the interpreter checks for events\n\ setdlopenflags() -- set the flags to be used for dlopen() calls\n\ setprofile() -- set the global profiling function\n\ setrecursionlimit() -- set the max recursion depth for the interpreter\n\ settrace() -- set the global debug tracing function\n\ " ) /* end of sys_doc */ ; PyDoc_STRVAR(flags__doc__, "sys.flags\n\ \n\ Flags provided through command line arguments or environment vars."); static PyTypeObject FlagsType; static PyStructSequence_Field flags_fields[] = { {"debug", "-d"}, {"inspect", "-i"}, {"interactive", "-i"}, {"optimize", "-O or -OO"}, {"dont_write_bytecode", "-B"}, {"no_user_site", "-s"}, {"no_site", "-S"}, {"ignore_environment", "-E"}, {"verbose", "-v"}, /* {"unbuffered", "-u"}, */ /* {"skip_first", "-x"}, */ {"bytes_warning", "-b"}, {"quiet", "-q"}, {"hash_randomization", "-R"}, {"isolated", "-I"}, {0} }; static PyStructSequence_Desc flags_desc = { "sys.flags", /* name */ flags__doc__, /* doc */ flags_fields, /* fields */ 13 }; static PyObject* make_flags(void) { int pos = 0; PyObject *seq; seq = PyStructSequence_New(&FlagsType); if (seq == NULL) return NULL; #define SetFlag(flag) \ PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag)) SetFlag(Py_DebugFlag); SetFlag(Py_InspectFlag); SetFlag(Py_InteractiveFlag); SetFlag(Py_OptimizeFlag); SetFlag(Py_DontWriteBytecodeFlag); SetFlag(Py_NoUserSiteDirectory); SetFlag(Py_NoSiteFlag); SetFlag(Py_IgnoreEnvironmentFlag); SetFlag(Py_VerboseFlag); /* SetFlag(saw_unbuffered_flag); */ /* SetFlag(skipfirstline); */ SetFlag(Py_BytesWarningFlag); SetFlag(Py_QuietFlag); SetFlag(Py_HashRandomizationFlag); SetFlag(Py_IsolatedFlag); #undef SetFlag if (PyErr_Occurred()) { Py_DECREF(seq); return NULL; } return seq; } PyDoc_STRVAR(version_info__doc__, "sys.version_info\n\ \n\ Version information as a named tuple."); static PyTypeObject VersionInfoType; static PyStructSequence_Field version_info_fields[] = { {"major", PyDoc_STR("Major release number")}, {"minor", PyDoc_STR("Minor release number")}, {"micro", PyDoc_STR("Patch release number")}, {"releaselevel", PyDoc_STR("'alpha', 'beta', 'candidate', or 'final'")}, {"serial", PyDoc_STR("Serial release number")}, {0} }; static PyStructSequence_Desc version_info_desc = { "sys.version_info", /* name */ version_info__doc__, /* doc */ version_info_fields, /* fields */ 5 }; static PyObject * make_version_info(void) { PyObject *version_info; char *s; int pos = 0; version_info = PyStructSequence_New(&VersionInfoType); if (version_info == NULL) { return NULL; } /* * These release level checks are mutually exclusive and cover * the field, so don't get too fancy with the pre-processor! */ #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA s = "alpha"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA s = "beta"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA s = "candidate"; #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL s = "final"; #endif #define SetIntItem(flag) \ PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag)) #define SetStrItem(flag) \ PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag)) SetIntItem(PY_MAJOR_VERSION); SetIntItem(PY_MINOR_VERSION); SetIntItem(PY_MICRO_VERSION); SetStrItem(s); SetIntItem(PY_RELEASE_SERIAL); #undef SetIntItem #undef SetStrItem if (PyErr_Occurred()) { Py_CLEAR(version_info); return NULL; } return version_info; } /* sys.implementation values */ #define NAME "cpython" const char *_PySys_ImplName = NAME; #define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION) #define MINOR Py_STRINGIFY(PY_MINOR_VERSION) #define TAG NAME "-" MAJOR MINOR const char *_PySys_ImplCacheTag = TAG; #undef NAME #undef MAJOR #undef MINOR #undef TAG static PyObject * make_impl_info(PyObject *version_info) { int res; PyObject *impl_info, *value, *ns; impl_info = PyDict_New(); if (impl_info == NULL) return NULL; /* populate the dict */ value = PyUnicode_FromString(_PySys_ImplName); if (value == NULL) goto error; res = PyDict_SetItemString(impl_info, "name", value); Py_DECREF(value); if (res < 0) goto error; value = PyUnicode_FromString(_PySys_ImplCacheTag); if (value == NULL) goto error; res = PyDict_SetItemString(impl_info, "cache_tag", value); Py_DECREF(value); if (res < 0) goto error; res = PyDict_SetItemString(impl_info, "version", version_info); if (res < 0) goto error; value = PyLong_FromLong(PY_VERSION_HEX); if (value == NULL) goto error; res = PyDict_SetItemString(impl_info, "hexversion", value); Py_DECREF(value); if (res < 0) goto error; #ifdef MULTIARCH value = PyUnicode_FromString(MULTIARCH); if (value == NULL) goto error; res = PyDict_SetItemString(impl_info, "_multiarch", value); Py_DECREF(value); if (res < 0) goto error; #endif /* dict ready */ ns = _PyNamespace_New(impl_info); Py_DECREF(impl_info); return ns; error: Py_CLEAR(impl_info); return NULL; } static struct PyModuleDef sysmodule = { PyModuleDef_HEAD_INIT, "sys", sys_doc, -1, /* multiple "initialization" just copies the module dict. */ sys_methods, NULL, NULL, NULL, NULL }; PyObject * _PySys_Init(void) { PyObject *m, *sysdict, *version_info; int res; m = PyModule_Create(&sysmodule); if (m == NULL) return NULL; sysdict = PyModule_GetDict(m); #define SET_SYS_FROM_STRING_BORROW(key, value) \ do { \ PyObject *v = (value); \ if (v == NULL) \ return NULL; \ res = PyDict_SetItemString(sysdict, key, v); \ if (res < 0) { \ return NULL; \ } \ } while (0) #define SET_SYS_FROM_STRING(key, value) \ do { \ PyObject *v = (value); \ if (v == NULL) \ return NULL; \ res = PyDict_SetItemString(sysdict, key, v); \ Py_DECREF(v); \ if (res < 0) { \ return NULL; \ } \ } while (0) /* Check that stdin is not a directory Using shell redirection, you can redirect stdin to a directory, crashing the Python interpreter. Catch this common mistake here and output a useful error message. Note that under MS Windows, the shell already prevents that. */ #if !defined(MS_WINDOWS) { struct _Py_stat_struct sb; if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 && S_ISDIR(sb.st_mode)) { /* There's nothing more we can do. */ /* Py_FatalError() will core dump, so just exit. */ PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n"); exit(EXIT_FAILURE); } } #endif /* stdin/stdout/stderr are set in pylifecycle.c */ SET_SYS_FROM_STRING_BORROW("__displayhook__", PyDict_GetItemString(sysdict, "displayhook")); SET_SYS_FROM_STRING_BORROW("__excepthook__", PyDict_GetItemString(sysdict, "excepthook")); SET_SYS_FROM_STRING("version", PyUnicode_FromString(Py_GetVersion())); SET_SYS_FROM_STRING("hexversion", PyLong_FromLong(PY_VERSION_HEX)); SET_SYS_FROM_STRING("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(), _Py_gitversion())); SET_SYS_FROM_STRING("dont_write_bytecode", PyBool_FromLong(Py_DontWriteBytecodeFlag)); SET_SYS_FROM_STRING("api_version", PyLong_FromLong(PYTHON_API_VERSION)); SET_SYS_FROM_STRING("copyright", PyUnicode_FromString(Py_GetCopyright())); SET_SYS_FROM_STRING("platform", PyUnicode_FromString(Py_GetPlatform())); SET_SYS_FROM_STRING("executable", PyUnicode_FromWideChar( Py_GetProgramFullPath(), -1)); SET_SYS_FROM_STRING("prefix", PyUnicode_FromWideChar(Py_GetPrefix(), -1)); SET_SYS_FROM_STRING("exec_prefix", PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); SET_SYS_FROM_STRING("base_prefix", PyUnicode_FromWideChar(Py_GetPrefix(), -1)); SET_SYS_FROM_STRING("base_exec_prefix", PyUnicode_FromWideChar(Py_GetExecPrefix(), -1)); SET_SYS_FROM_STRING("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX)); SET_SYS_FROM_STRING("float_info", PyFloat_GetInfo()); SET_SYS_FROM_STRING("int_info", PyLong_GetInfo()); /* initialize hash_info */ if (Hash_InfoType.tp_name == NULL) { if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) return NULL; } SET_SYS_FROM_STRING("hash_info", get_hash_info()); SET_SYS_FROM_STRING("maxunicode", PyLong_FromLong(0x10FFFF)); SET_SYS_FROM_STRING("builtin_module_names", list_builtin_module_names()); #if PY_BIG_ENDIAN SET_SYS_FROM_STRING("byteorder", PyUnicode_FromString("big")); #else SET_SYS_FROM_STRING("byteorder", PyUnicode_FromString("little")); #endif #ifdef MS_COREDLL SET_SYS_FROM_STRING("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule)); SET_SYS_FROM_STRING("winver", PyUnicode_FromString(PyWin_DLLVersionString)); #endif #ifdef ABIFLAGS SET_SYS_FROM_STRING("abiflags", PyUnicode_FromString(ABIFLAGS)); #endif if (warnoptions == NULL) { warnoptions = PyList_New(0); if (warnoptions == NULL) return NULL; } else { Py_INCREF(warnoptions); } SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions); SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions()); /* version_info */ if (VersionInfoType.tp_name == NULL) { if (PyStructSequence_InitType2(&VersionInfoType, &version_info_desc) < 0) return NULL; } version_info = make_version_info(); SET_SYS_FROM_STRING("version_info", version_info); /* prevent user from creating new instances */ VersionInfoType.tp_init = NULL; VersionInfoType.tp_new = NULL; res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__"); if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) PyErr_Clear(); /* implementation */ SET_SYS_FROM_STRING("implementation", make_impl_info(version_info)); /* flags */ if (FlagsType.tp_name == 0) { if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) return NULL; } SET_SYS_FROM_STRING("flags", make_flags()); /* prevent user from creating new instances */ FlagsType.tp_init = NULL; FlagsType.tp_new = NULL; res = PyDict_DelItemString(FlagsType.tp_dict, "__new__"); if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) PyErr_Clear(); /* getwindowsversion */ if (WindowsVersionType.tp_name == 0) if (PyStructSequence_InitType2(&WindowsVersionType, &windows_version_desc) < 0) return NULL; /* prevent user from creating new instances */ WindowsVersionType.tp_init = NULL; WindowsVersionType.tp_new = NULL; res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__"); if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) PyErr_Clear(); /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */ #ifndef PY_NO_SHORT_FLOAT_REPR SET_SYS_FROM_STRING("float_repr_style", PyUnicode_FromString("short")); #else SET_SYS_FROM_STRING("float_repr_style", PyUnicode_FromString("legacy")); #endif #ifdef WITH_THREAD SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo()); #endif /* initialize asyncgen_hooks */ if (AsyncGenHooksType.tp_name == NULL) { if (PyStructSequence_InitType2( &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) { return NULL; } } #undef SET_SYS_FROM_STRING #undef SET_SYS_FROM_STRING_BORROW if (PyErr_Occurred()) return NULL; return m; } static PyObject * makepathobject(const wchar_t *path, wchar_t delim) { int i, n; const wchar_t *p; PyObject *v, *w; n = 1; p = path; while ((p = wcschr(p, delim)) != NULL) { n++; p++; } v = PyList_New(n); if (v == NULL) return NULL; for (i = 0; ; i++) { p = wcschr(path, delim); if (p == NULL) p = path + wcslen(path); /* End of string */ w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path)); if (w == NULL) { Py_DECREF(v); return NULL; } PyList_SET_ITEM(v, i, w); if (*p == '\0') break; path = p+1; } return v; } void PySys_SetPath(const wchar_t *path) { PyObject *v; int delim = DELIM; if(IsWindows()) delim = L';'; if ((v = makepathobject(path, delim)) == NULL) Py_FatalError("can't create sys.path"); if (_PySys_SetObjectId(&PyId_path, v) != 0) Py_FatalError("can't assign sys.path"); Py_DECREF(v); } static PyObject * makeargvobject(int argc, wchar_t **argv) { PyObject *av; if (argc <= 0 || argv == NULL) { /* Ensure at least one (empty) argument is seen */ static wchar_t *empty_argv[1] = {L""}; argv = empty_argv; argc = 1; } av = PyList_New(argc); if (av != NULL) { int i; for (i = 0; i < argc; i++) { PyObject *v = PyUnicode_FromWideChar(argv[i], -1); if (v == NULL) { Py_DECREF(av); av = NULL; break; } PyList_SetItem(av, i, v); } } return av; } #define _HAVE_SCRIPT_ARGUMENT(argc, argv) \ (argc > 0 && argv0 != NULL && \ wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0) static void sys_update_path(int argc, wchar_t **argv) { wchar_t *argv0; wchar_t *p = NULL; Py_ssize_t n = 0; PyObject *a; PyObject *path; #ifdef HAVE_READLINK wchar_t *link = gc(calloc(MAXPATHLEN+1, sizeof(wchar_t))); wchar_t *argv0copy = gc(calloc(2*MAXPATHLEN+1, sizeof(wchar_t))); int nr = 0; #endif #if defined(HAVE_REALPATH) wchar_t *fullpath = gc(calloc(MAXPATHLEN, sizeof(wchar_t))); #elif defined(MS_WINDOWS) wchar_t *fullpath = gc(calloc(MAX_PATH, sizeof(wchar_t))); #endif path = _PySys_GetObjectId(&PyId_path); if (path == NULL) return; argv0 = argv[0]; #ifdef HAVE_READLINK if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) nr = _Py_wreadlink(argv0, link, MAXPATHLEN); if (nr > 0) { /* It's a symlink */ link[nr] = '\0'; if (link[0] == SEP) argv0 = link; /* Link to absolute path */ else if (wcschr(link, SEP) == NULL) ; /* Link without path */ else { /* Must join(dirname(argv0), link) */ wchar_t *q = wcsrchr(argv0, SEP); if (q == NULL) argv0 = link; /* argv0 without path */ else { /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */ wcsncpy(argv0copy, argv0, MAXPATHLEN); q = wcsrchr(argv0copy, SEP); wcsncpy(q+1, link, MAXPATHLEN); q[MAXPATHLEN + 1] = L'\0'; argv0 = argv0copy; } } } #endif /* HAVE_READLINK */ #if SEP == '\\' /* Special case for MS filename syntax */ if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) { wchar_t *q; #if defined(MS_WINDOWS) /* Replace the first element in argv with the full path. */ wchar_t *ptemp; if (GetFullPathNameW(argv0, MAX_PATH, fullpath, &ptemp)) { argv0 = fullpath; } #endif p = wcsrchr(argv0, SEP); /* Test for alternate separator */ q = wcsrchr(p ? p : argv0, '/'); if (q != NULL) p = q; if (p != NULL) { n = p + 1 - argv0; if (n > 1 && p[-1] != ':') n--; /* Drop trailing separator */ } } #else /* All other filename syntaxes */ if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) { #if defined(HAVE_REALPATH) if (_Py_wrealpath(argv0, fullpath, MAXPATHLEN)) { argv0 = fullpath; } #endif p = wcsrchr(argv0, SEP); } if (p != NULL) { n = p + 1 - argv0; #if SEP == '/' /* Special case for Unix filename syntax */ if (n > 1 && (!IsWindows() || p[-1] != ':')) n--; /* Drop trailing separator */ #endif /* Unix */ } #endif /* All others */ a = PyUnicode_FromWideChar(argv0, n); if (a == NULL) Py_FatalError("no mem for sys.path insertion"); if (PyList_Insert(path, 0, a) < 0) Py_FatalError("sys.path.insert(0) failed"); Py_DECREF(a); } void PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath) { PyObject *av = makeargvobject(argc, argv); if (av == NULL) Py_FatalError("no mem for sys.argv"); if (PySys_SetObject("argv", av) != 0) Py_FatalError("can't assign sys.argv"); Py_DECREF(av); if (updatepath) sys_update_path(argc, argv); } void PySys_SetArgv(int argc, wchar_t **argv) { PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0); } /* Reimplementation of PyFile_WriteString() no calling indirectly PyErr_CheckSignals(): avoid the call to PyObject_Str(). */ static int sys_pyfile_write_unicode(PyObject *unicode, PyObject *file) { PyObject *writer = NULL, *result = NULL; int err; if (file == NULL) return -1; writer = _PyObject_GetAttrId(file, &PyId_write); if (writer == NULL) goto error; result = _PyObject_CallArg1(writer, unicode); if (result == NULL) { goto error; } else { err = 0; goto finally; } error: err = -1; finally: Py_XDECREF(writer); Py_XDECREF(result); return err; } static int sys_pyfile_write(const char *text, PyObject *file) { PyObject *unicode = NULL; int err; if (file == NULL) return -1; unicode = PyUnicode_FromString(text); if (unicode == NULL) return -1; err = sys_pyfile_write_unicode(unicode, file); Py_DECREF(unicode); return err; } /* APIs to write to sys.stdout or sys.stderr using a printf-like interface. Adapted from code submitted by Just van Rossum. PySys_WriteStdout(format, ...) PySys_WriteStderr(format, ...) The first function writes to sys.stdout; the second to sys.stderr. When there is a problem, they write to the real (C level) stdout or stderr; no exceptions are raised. PyErr_CheckSignals() is not called to avoid the execution of the Python signal handlers: they may raise a new exception whereas sys_write() ignores all exceptions. Both take a printf-style format string as their first argument followed by a variable length argument list determined by the format string. *** WARNING *** The format should limit the total size of the formatted output string to 1000 bytes. In particular, this means that no unrestricted "%s" formats should occur; these should be limited using "%.<N>s where <N> is a decimal number calculated so that <N> plus the maximum size of other formatted text does not exceed 1000 bytes. Also watch out for "%f", which can print hundreds of digits for very large numbers. */ static void sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va) { PyObject *file; PyObject *error_type, *error_value, *error_traceback; char buffer[1001]; int written; PyErr_Fetch(&error_type, &error_value, &error_traceback); file = _PySys_GetObjectId(key); written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va); if (sys_pyfile_write(buffer, file) != 0) { PyErr_Clear(); fputs(buffer, fp); } if (written < 0 || (size_t)written >= sizeof(buffer)) { const char *truncated = "... truncated"; if (sys_pyfile_write(truncated, file) != 0) fputs(truncated, fp); } PyErr_Restore(error_type, error_value, error_traceback); } void PySys_WriteStdout(const char *format, ...) { va_list va; va_start(va, format); sys_write(&PyId_stdout, stdout, format, va); va_end(va); } void PySys_WriteStderr(const char *format, ...) { va_list va; va_start(va, format); sys_write(&PyId_stderr, stderr, format, va); va_end(va); } static void sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va) { PyObject *file, *message; PyObject *error_type, *error_value, *error_traceback; char *utf8; PyErr_Fetch(&error_type, &error_value, &error_traceback); file = _PySys_GetObjectId(key); message = PyUnicode_FromFormatV(format, va); if (message != NULL) { if (sys_pyfile_write_unicode(message, file) != 0) { PyErr_Clear(); utf8 = PyUnicode_AsUTF8(message); if (utf8 != NULL) fputs(utf8, fp); } Py_DECREF(message); } PyErr_Restore(error_type, error_value, error_traceback); } void PySys_FormatStdout(const char *format, ...) { va_list va; va_start(va, format); sys_format(&PyId_stdout, stdout, format, va); va_end(va); } void PySys_FormatStderr(const char *format, ...) { va_list va; va_start(va, format); sys_format(&PyId_stderr, stderr, format, va); va_end(va); }
76,663
2,535
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/mystrtoul.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/errno.h" #include "libc/limits.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/pyconfig.h" /* clang-format off */ /* Static overflow check values for bases 2 through 36. * smallmax[base] is the largest unsigned long i such that * i * base doesn't overflow unsigned long. */ static const unsigned long smallmax[] = { 0, /* bases 0 and 1 are invalid */ 0, ULONG_MAX / 2, ULONG_MAX / 3, ULONG_MAX / 4, ULONG_MAX / 5, ULONG_MAX / 6, ULONG_MAX / 7, ULONG_MAX / 8, ULONG_MAX / 9, ULONG_MAX / 10, ULONG_MAX / 11, ULONG_MAX / 12, ULONG_MAX / 13, ULONG_MAX / 14, ULONG_MAX / 15, ULONG_MAX / 16, ULONG_MAX / 17, ULONG_MAX / 18, ULONG_MAX / 19, ULONG_MAX / 20, ULONG_MAX / 21, ULONG_MAX / 22, ULONG_MAX / 23, ULONG_MAX / 24, ULONG_MAX / 25, ULONG_MAX / 26, ULONG_MAX / 27, ULONG_MAX / 28, ULONG_MAX / 29, ULONG_MAX / 30, ULONG_MAX / 31, ULONG_MAX / 32, ULONG_MAX / 33, ULONG_MAX / 34, ULONG_MAX / 35, ULONG_MAX / 36, }; /* maximum digits that can't ever overflow for bases 2 through 36, * calculated by [int(math.floor(math.log(2**32, i))) for i in range(2, 37)]. * Note that this is pessimistic if sizeof(long) > 4. */ #if SIZEOF_LONG == 4 static const int digitlimit[] = { 0, 0, 32, 20, 16, 13, 12, 11, 10, 10, /* 0 - 9 */ 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, /* 10 - 19 */ 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, /* 20 - 29 */ 6, 6, 6, 6, 6, 6, 6}; /* 30 - 36 */ #elif SIZEOF_LONG == 8 /* [int(math.floor(math.log(2**64, i))) for i in range(2, 37)] */ static const int digitlimit[] = { 0, 0, 64, 40, 32, 27, 24, 22, 21, 20, /* 0 - 9 */ 19, 18, 17, 17, 16, 16, 16, 15, 15, 15, /* 10 - 19 */ 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, /* 20 - 29 */ 13, 12, 12, 12, 12, 12, 12}; /* 30 - 36 */ #else #error "Need table for SIZEOF_LONG" #endif /* ** strtoul ** This is a general purpose routine for converting ** an ascii string to an integer in an arbitrary base. ** Leading white space is ignored. If 'base' is zero ** it looks for a leading 0b, 0o or 0x to tell which ** base. If these are absent it defaults to 10. ** Base must be 0 or between 2 and 36 (inclusive). ** If 'ptr' is non-NULL it will contain a pointer to ** the end of the scan. ** Errors due to bad pointers will probably result in ** exceptions - we don't check for them. */ unsigned long PyOS_strtoul(const char *str, char **ptr, int base) { unsigned long result = 0; /* return value of the function */ int c; /* current input character */ int ovlimit; /* required digits to overflow */ /* skip leading white space */ while (*str && Py_ISSPACE(Py_CHARMASK(*str))) ++str; /* check for leading 0b, 0o or 0x for auto-base or base 16 */ switch (base) { case 0: /* look for leading 0b, 0o or 0x */ if (*str == '0') { ++str; if (*str == 'x' || *str == 'X') { /* there must be at least one digit after 0x */ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { if (ptr) *ptr = (char *)str; return 0; } ++str; base = 16; } else if (*str == 'o' || *str == 'O') { /* there must be at least one digit after 0o */ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { if (ptr) *ptr = (char *)str; return 0; } ++str; base = 8; } else if (*str == 'b' || *str == 'B') { /* there must be at least one digit after 0b */ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { if (ptr) *ptr = (char *)str; return 0; } ++str; base = 2; } else { /* skip all zeroes... */ while (*str == '0') ++str; if ('0' <= *str && *str <= '7') { base = 8; /* [jart] restore octal */ } else { while (Py_ISSPACE(Py_CHARMASK(*str))) ++str; if (ptr) *ptr = (char *)str; return 0; } } } else base = 10; break; /* even with explicit base, skip leading 0? prefix */ case 16: if (*str == '0') { ++str; if (*str == 'x' || *str == 'X') { /* there must be at least one digit after 0x */ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) { if (ptr) *ptr = (char *)str; return 0; } ++str; } } break; case 8: if (*str == '0') { ++str; if (*str == 'o' || *str == 'O') { /* there must be at least one digit after 0o */ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) { if (ptr) *ptr = (char *)str; return 0; } ++str; } } break; case 2: if(*str == '0') { ++str; if (*str == 'b' || *str == 'B') { /* there must be at least one digit after 0b */ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) { if (ptr) *ptr = (char *)str; return 0; } ++str; } } break; } /* catch silly bases */ if (base < 2 || base > 36) { if (ptr) *ptr = (char *)str; return 0; } /* skip leading zeroes */ while (*str == '0') ++str; /* base is guaranteed to be in [2, 36] at this point */ ovlimit = digitlimit[base]; /* do the conversion until non-digit character encountered */ while ((c = _PyLong_DigitValue[Py_CHARMASK(*str)]) < base) { if (ovlimit > 0) /* no overflow check required */ result = result * base + c; else { /* requires overflow check */ unsigned long temp_result; if (ovlimit < 0) /* guaranteed overflow */ goto overflowed; /* there could be an overflow */ /* check overflow just from shifting */ if (result > smallmax[base]) goto overflowed; result *= base; /* check overflow from the digit's value */ temp_result = result + c; if (temp_result < result) goto overflowed; result = temp_result; } ++str; --ovlimit; } /* set pointer to point to the last character scanned */ if (ptr) *ptr = (char *)str; return result; overflowed: if (ptr) { /* spool through remaining digit characters */ while (_PyLong_DigitValue[Py_CHARMASK(*str)] < base) ++str; *ptr = (char *)str; } errno = ERANGE; return (unsigned long)-1; } /* Checking for overflow in PyOS_strtol is a PITA; see comments * about PY_ABS_LONG_MIN in longobject.c. */ #define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN) long PyOS_strtol(const char *str, char **ptr, int base) { long result; unsigned long uresult; char sign; while (*str && Py_ISSPACE(Py_CHARMASK(*str))) str++; sign = *str; if (sign == '+' || sign == '-') str++; uresult = PyOS_strtoul(str, ptr, base); if (uresult <= (unsigned long)LONG_MAX) { result = (long)uresult; if (sign == '-') result = -result; } else if (sign == '-' && uresult == PY_ABS_LONG_MIN) { result = LONG_MIN; } else { errno = ERANGE; result = LONG_MAX; } return result; }
9,346
295
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/future.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/graminit.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/symtable.h" #include "third_party/python/Include/token.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ #define UNDEFINED_FUTURE_FEATURE "future feature %.100s is not defined" #define ERR_LATE_FUTURE \ "from __future__ imports must occur at the beginning of the file" static int future_check_features(PyFutureFeatures *ff, stmt_ty s, PyObject *filename) { int i; asdl_seq *names; assert(s->kind == ImportFrom_kind); names = s->v.ImportFrom.names; for (i = 0; i < asdl_seq_LEN(names); i++) { alias_ty name = (alias_ty)asdl_seq_GET(names, i); const char *feature = PyUnicode_AsUTF8(name->name); if (!feature) return 0; if (strcmp(feature, FUTURE_NESTED_SCOPES) == 0) { continue; } else if (strcmp(feature, FUTURE_GENERATORS) == 0) { continue; } else if (strcmp(feature, FUTURE_DIVISION) == 0) { continue; } else if (strcmp(feature, FUTURE_ABSOLUTE_IMPORT) == 0) { continue; } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) { continue; } else if (strcmp(feature, FUTURE_PRINT_FUNCTION) == 0) { continue; } else if (strcmp(feature, FUTURE_UNICODE_LITERALS) == 0) { continue; } else if (strcmp(feature, FUTURE_BARRY_AS_BDFL) == 0) { ff->ff_features |= CO_FUTURE_BARRY_AS_BDFL; } else if (strcmp(feature, FUTURE_GENERATOR_STOP) == 0) { ff->ff_features |= CO_FUTURE_GENERATOR_STOP; } else if (strcmp(feature, "braces") == 0) { PyErr_SetString(PyExc_SyntaxError, "not a chance"); PyErr_SyntaxLocationObject(filename, s->lineno, s->col_offset); return 0; } else { PyErr_Format(PyExc_SyntaxError, UNDEFINED_FUTURE_FEATURE, feature); PyErr_SyntaxLocationObject(filename, s->lineno, s->col_offset); return 0; } } return 1; } static int future_parse(PyFutureFeatures *ff, mod_ty mod, PyObject *filename) { int i, done = 0, prev_line = 0; stmt_ty first; if (!(mod->kind == Module_kind || mod->kind == Interactive_kind)) return 1; if (asdl_seq_LEN(mod->v.Module.body) == 0) return 1; /* A subsequent pass will detect future imports that don't appear at the beginning of the file. There's one case, however, that is easier to handle here: A series of imports joined by semi-colons, where the first import is a future statement but some subsequent import has the future form but is preceded by a regular import. */ i = 0; first = (stmt_ty)asdl_seq_GET(mod->v.Module.body, i); if (first->kind == Expr_kind && (first->v.Expr.value->kind == Str_kind || (first->v.Expr.value->kind == Constant_kind && PyUnicode_CheckExact(first->v.Expr.value->v.Constant.value)))) i++; for (; i < asdl_seq_LEN(mod->v.Module.body); i++) { stmt_ty s = (stmt_ty)asdl_seq_GET(mod->v.Module.body, i); if (done && s->lineno > prev_line) return 1; prev_line = s->lineno; /* The tests below will return from this function unless it is still possible to find a future statement. The only things that can precede a future statement are another future statement and a doc string. */ if (s->kind == ImportFrom_kind) { identifier modname = s->v.ImportFrom.module; if (modname && _PyUnicode_EqualToASCIIString(modname, "__future__")) { if (done) { PyErr_SetString(PyExc_SyntaxError, ERR_LATE_FUTURE); PyErr_SyntaxLocationObject(filename, s->lineno, s->col_offset); return 0; } if (!future_check_features(ff, s, filename)) return 0; ff->ff_lineno = s->lineno; } else { done = 1; } } else { done = 1; } } return 1; } PyFutureFeatures * PyFuture_FromASTObject(mod_ty mod, PyObject *filename) { PyFutureFeatures *ff; ff = (PyFutureFeatures *)PyObject_Malloc(sizeof(PyFutureFeatures)); if (ff == NULL) { PyErr_NoMemory(); return NULL; } ff->ff_features = 0; ff->ff_lineno = -1; if (!future_parse(ff, mod, filename)) { PyObject_Free(ff); return NULL; } return ff; } PyFutureFeatures * PyFuture_FromAST(mod_ty mod, const char *filename_str) { PyFutureFeatures *ff; PyObject *filename; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) return NULL; ff = PyFuture_FromASTObject(mod, filename); Py_DECREF(filename); return ff; }
6,117
155
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pymath.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/pyconfig.h" /* clang-format off */ #ifdef X87_DOUBLE_ROUNDING /* On x86 platforms using an x87 FPU, this function is called from the Py_FORCE_DOUBLE macro (defined in pymath.h) to force a floating-point number out of an 80-bit x87 FPU register and into a 64-bit memory location, thus rounding from extended precision to double precision. */ double _Py_force_double(double x) { volatile double y; y = x; return y; } #endif #ifdef HAVE_GCC_ASM_FOR_X87 /* inline assembly for getting and setting the 387 FPU control word on gcc/x86 */ #ifdef _Py_MEMORY_SANITIZER __attribute__((no_sanitize_memory)) #endif unsigned short _Py_get_387controlword(void) { unsigned short cw; __asm__ __volatile__ ("fnstcw %0" : "=m" (cw)); return cw; } void _Py_set_387controlword(unsigned short cw) { __asm__ __volatile__ ("fldcw %0" : : "m" (cw)); } #endif
1,722
38
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/thread.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/struct/timespec.h" #include "libc/calls/struct/timeval.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/thread/thread2.h" #include "third_party/python/Include/dynamic_annotations.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pythread.h" #include "third_party/python/Include/structseq.h" #include "third_party/python/pyconfig.h" /* clang-format off */ /* Thread package. This is intended to be usable independently from Python. The implementation for system foobar is in a file thread_foobar.inc which is included by this file dependent on config settings. Stuff shared by all thread_*.h files is collected here. */ #ifndef _POSIX_THREADS /* Check if we're running on HP-UX and _SC_THREADS is defined. If so, then enough of the Posix threads package is implemented to support python threads. This is valid for HP-UX 11.23 running on an ia64 system. If needed, add a check of __ia64 to verify that we're running on an ia64 system instead of a pa-risc system. */ #ifdef __hpux #ifdef _SC_THREADS #define _POSIX_THREADS #endif #endif #endif /* _POSIX_THREADS */ #ifdef Py_DEBUG static int thread_debug = 0; #define dprintf(args) (void)((thread_debug & 1) && printf args) #define d2printf(args) ((thread_debug & 8) && printf args) #else #define dprintf(args) #define d2printf(args) #endif static int initialized; static void PyThread__init_thread(void); /* Forward */ void PyThread_init_thread(void) { #ifdef Py_DEBUG char *p = Py_GETENV("PYTHONTHREADDEBUG"); if (p) { if (*p) thread_debug = atoi(p); else thread_debug = 1; } #endif /* Py_DEBUG */ if (initialized) return; initialized = 1; dprintf(("PyThread_init_thread called\n")); PyThread__init_thread(); } /* Support for runtime thread stack size tuning. A value of 0 means using the platform's default stack size or the size specified by the THREAD_STACK_SIZE macro. */ static size_t _pythread_stacksize = 0; #ifdef _POSIX_THREADS #define PYTHREAD_NAME "pthread" #include "third_party/python/Python/thread_pthread.inc" #endif #ifdef NT_THREADS #define PYTHREAD_NAME "nt" // #include "thread_nt.inc" #endif /* #ifdef FOOBAR_THREADS // #include "thread_foobar.inc" #endif */ /* return the current thread stack size */ size_t PyThread_get_stacksize(void) { return _pythread_stacksize; } /* Only platforms defining a THREAD_SET_STACKSIZE() macro in thread_<platform>.h support changing the stack size. Return 0 if stack size is valid, -1 if stack size value is invalid, -2 if setting stack size is not supported. */ int PyThread_set_stacksize(size_t size) { #if defined(THREAD_SET_STACKSIZE) return THREAD_SET_STACKSIZE(size); #else return -2; #endif } #ifndef Py_HAVE_NATIVE_TLS /* If the platform has not supplied a platform specific TLS implementation, provide our own. This code stolen from "thread_sgi.h", where it was the only implementation of an existing Python TLS API. */ /* ------------------------------------------------------------------------ Per-thread data ("key") support. Use PyThread_create_key() to create a new key. This is typically shared across threads. Use PyThread_set_key_value(thekey, value) to associate void* value with thekey in the current thread. Each thread has a distinct mapping of thekey to a void* value. Caution: if the current thread already has a mapping for thekey, value is ignored. Use PyThread_get_key_value(thekey) to retrieve the void* value associated with thekey in the current thread. This returns NULL if no value is associated with thekey in the current thread. Use PyThread_delete_key_value(thekey) to forget the current thread's associated value for thekey. PyThread_delete_key(thekey) forgets the values associated with thekey across *all* threads. While some of these functions have error-return values, none set any Python exception. None of the functions does memory management on behalf of the void* values. You need to allocate and deallocate them yourself. If the void* values happen to be PyObject*, these functions don't do refcount operations on them either. The GIL does not need to be held when calling these functions; they supply their own locking. This isn't true of PyThread_create_key(), though (see next paragraph). There's a hidden assumption that PyThread_create_key() will be called before any of the other functions are called. There's also a hidden assumption that calls to PyThread_create_key() are serialized externally. ------------------------------------------------------------------------ */ /* A singly-linked list of struct key objects remembers all the key->value * associations. File static keyhead heads the list. keymutex is used * to enforce exclusion internally. */ struct key { /* Next record in the list, or NULL if this is the last record. */ struct key *next; /* The thread id, according to PyThread_get_thread_ident(). */ long id; /* The key and its associated value. */ int key; void *value; }; static struct key *keyhead = NULL; static PyThread_type_lock keymutex = NULL; static int nkeys = 0; /* PyThread_create_key() hands out nkeys+1 next */ /* Internal helper. * If the current thread has a mapping for key, the appropriate struct key* * is returned. NB: value is ignored in this case! * If there is no mapping for key in the current thread, then: * If value is NULL, NULL is returned. * Else a mapping of key to value is created for the current thread, * and a pointer to a new struct key* is returned; except that if * malloc() can't find room for a new struct key*, NULL is returned. * So when value==NULL, this acts like a pure lookup routine, and when * value!=NULL, this acts like dict.setdefault(), returning an existing * mapping if one exists, else creating a new mapping. * * Caution: this used to be too clever, trying to hold keymutex only * around the "p->next = keyhead; keyhead = p" pair. That allowed * another thread to mutate the list, via key deletion, concurrent with * find_key() crawling over the list. Hilarity ensued. For example, when * the for-loop here does "p = p->next", p could end up pointing at a * record that PyThread_delete_key_value() was concurrently free()'ing. * That could lead to anything, from failing to find a key that exists, to * segfaults. Now we lock the whole routine. */ static struct key * find_key(int set_value, int key, void *value) { struct key *p, *prev_p; long id = PyThread_get_thread_ident(); if (!keymutex) return NULL; PyThread_acquire_lock(keymutex, 1); prev_p = NULL; for (p = keyhead; p != NULL; p = p->next) { if (p->id == id && p->key == key) { if (set_value) p->value = value; goto Done; } /* Sanity check. These states should never happen but if * they do we must abort. Otherwise we'll end up spinning * in a tight loop with the lock held. A similar check is done * in pystate.c tstate_delete_common(). */ if (p == prev_p) Py_FatalError("tls find_key: small circular list(!)"); prev_p = p; if (p->next == keyhead) Py_FatalError("tls find_key: circular list(!)"); } if (!set_value && value == NULL) { assert(p == NULL); goto Done; } p = (struct key *)PyMem_RawMalloc(sizeof(struct key)); if (p != NULL) { p->id = id; p->key = key; p->value = value; p->next = keyhead; keyhead = p; } Done: PyThread_release_lock(keymutex); return p; } /* Return a new key. This must be called before any other functions in * this family, and callers must arrange to serialize calls to this * function. No violations are detected. */ int PyThread_create_key(void) { /* All parts of this function are wrong if it's called by multiple * threads simultaneously. */ if (keymutex == NULL) keymutex = PyThread_allocate_lock(); return ++nkeys; } /* Forget the associations for key across *all* threads. */ void PyThread_delete_key(int key) { struct key *p, **q; PyThread_acquire_lock(keymutex, 1); q = &keyhead; while ((p = *q) != NULL) { if (p->key == key) { *q = p->next; PyMem_RawFree((void *)p); /* NB This does *not* free p->value! */ } else q = &p->next; } PyThread_release_lock(keymutex); } int PyThread_set_key_value(int key, void *value) { struct key *p; p = find_key(1, key, value); if (p == NULL) return -1; else return 0; } /* Retrieve the value associated with key in the current thread, or NULL * if the current thread doesn't have an association for key. */ void * PyThread_get_key_value(int key) { struct key *p = find_key(0, key, NULL); if (p == NULL) return NULL; else return p->value; } /* Forget the current thread's association for key, if any. */ void PyThread_delete_key_value(int key) { long id = PyThread_get_thread_ident(); struct key *p, **q; PyThread_acquire_lock(keymutex, 1); q = &keyhead; while ((p = *q) != NULL) { if (p->key == key && p->id == id) { *q = p->next; PyMem_RawFree((void *)p); /* NB This does *not* free p->value! */ break; } else q = &p->next; } PyThread_release_lock(keymutex); } /* Forget everything not associated with the current thread id. * This function is called from PyOS_AfterFork(). It is necessary * because other thread ids which were in use at the time of the fork * may be reused for new threads created in the forked process. */ void PyThread_ReInitTLS(void) { long id = PyThread_get_thread_ident(); struct key *p, **q; if (!keymutex) return; /* As with interpreter_lock in PyEval_ReInitThreads() we just create a new lock without freeing the old one */ keymutex = PyThread_allocate_lock(); /* Delete all keys which do not match the current thread id */ q = &keyhead; while ((p = *q) != NULL) { if (p->id != id) { *q = p->next; PyMem_RawFree((void *)p); /* NB This does *not* free p->value! */ } else q = &p->next; } } #endif /* Py_HAVE_NATIVE_TLS */ PyDoc_STRVAR(threadinfo__doc__, "sys.thread_info\n\ \n\ A struct sequence holding information about the thread implementation."); static PyStructSequence_Field threadinfo_fields[] = { {"name", PyDoc_STR("name of the thread implementation")}, {"lock", PyDoc_STR("name of the lock implementation")}, {"version", PyDoc_STR("name and version of the thread library")}, {0} }; static PyStructSequence_Desc threadinfo_desc = { "sys.thread_info", /* name */ threadinfo__doc__, /* doc */ threadinfo_fields, /* fields */ 3 }; static PyTypeObject ThreadInfoType; PyObject* PyThread_GetInfo(void) { PyObject *threadinfo, *value; int pos = 0; #if (defined(_POSIX_THREADS) && defined(HAVE_CONFSTR) \ && defined(_CS_GNU_LIBPTHREAD_VERSION)) char buffer[255]; int len; #endif if (ThreadInfoType.tp_name == 0) { if (PyStructSequence_InitType2(&ThreadInfoType, &threadinfo_desc) < 0) return NULL; } threadinfo = PyStructSequence_New(&ThreadInfoType); if (threadinfo == NULL) return NULL; value = PyUnicode_FromString(PYTHREAD_NAME); if (value == NULL) { Py_DECREF(threadinfo); return NULL; } PyStructSequence_SET_ITEM(threadinfo, pos++, value); #ifdef _POSIX_THREADS #ifdef USE_SEMAPHORES value = PyUnicode_FromString("semaphore"); #else value = PyUnicode_FromString("mutex+cond"); #endif if (value == NULL) { Py_DECREF(threadinfo); return NULL; } #else Py_INCREF(Py_None); value = Py_None; #endif PyStructSequence_SET_ITEM(threadinfo, pos++, value); #if (defined(_POSIX_THREADS) && defined(HAVE_CONFSTR) \ && defined(_CS_GNU_LIBPTHREAD_VERSION)) value = NULL; len = confstr(_CS_GNU_LIBPTHREAD_VERSION, buffer, sizeof(buffer)); if (1 < len && (size_t)len < sizeof(buffer)) { value = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1); if (value == NULL) PyErr_Clear(); } if (value == NULL) #endif { Py_INCREF(Py_None); value = Py_None; } PyStructSequence_SET_ITEM(threadinfo, pos++, value); return threadinfo; }
13,752
450
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pyhash.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "third_party/python/Include/pyhash.h" /* clang-format off */ /* Set of hash utility functions to help maintaining the invariant that if a==b then hash(a)==hash(b) All the utility functions (_Py_Hash*()) return "-1" to signify an error. */ _Py_HashSecret_t _Py_HashSecret; #if Py_HASH_ALGORITHM == Py_HASH_EXTERNAL extern PyHash_FuncDef PyHash_Func; #else static PyHash_FuncDef PyHash_Func; #endif /* Count _Py_HashBytes() calls */ #ifdef Py_HASH_STATS #define Py_HASH_STATS_MAX 32 static Py_ssize_t hashstats[Py_HASH_STATS_MAX + 1] = {0}; #endif /* For numeric types, the hash of a number x is based on the reduction of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that hash(x) == hash(y) whenever x and y are numerically equal, even if x and y have different types. A quick summary of the hashing strategy: (1) First define the 'reduction of x modulo P' for any rational number x; this is a standard extension of the usual notion of reduction modulo P for integers. If x == p/q (written in lowest terms), the reduction is interpreted as the reduction of p times the inverse of the reduction of q, all modulo P; if q is exactly divisible by P then define the reduction to be infinity. So we've got a well-defined map reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }. (2) Now for a rational number x, define hash(x) by: reduce(x) if x >= 0 -reduce(-x) if x < 0 If the result of the reduction is infinity (this is impossible for integers, floats and Decimals) then use the predefined hash value _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead. _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the hashes of float and Decimal infinities and nans. A selling point for the above strategy is that it makes it possible to compute hashes of decimal and binary floating-point numbers efficiently, even if the exponent of the binary or decimal number is large. The key point is that reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS) provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a binary or decimal float is never infinity, since the denominator is a power of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have, for nonnegative x, reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS and reduce(10**e) can be computed efficiently by the usual modular exponentiation algorithm. For reduce(2**e) it's even better: since P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits. */ Py_hash_t _Py_HashDouble(double v) { int e, sign; double m; Py_uhash_t x, y; if (!Py_IS_FINITE(v)) { if (Py_IS_INFINITY(v)) return v > 0 ? _PyHASH_INF : -_PyHASH_INF; else return _PyHASH_NAN; } m = frexp(v, &e); sign = 1; if (m < 0) { sign = -1; m = -m; } /* process 28 bits at a time; this should work well both for binary and hexadecimal floating point. */ x = 0; while (m) { x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28); m *= 268435456.0; /* 2**28 */ e -= 28; y = (Py_uhash_t)m; /* pull out integer part */ m -= y; x += y; if (x >= _PyHASH_MODULUS) x -= _PyHASH_MODULUS; } /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */ e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS); x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e); x = x * sign; if (x == (Py_uhash_t)-1) x = (Py_uhash_t)-2; return (Py_hash_t)x; } Py_hash_t _Py_HashPointer(void *p) { Py_hash_t x; size_t y = (size_t)p; /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid excessive hash collisions for dicts and sets */ y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4)); x = (Py_hash_t)y; if (x == -1) x = -2; return x; } Py_hash_t _Py_HashBytes(const void *src, Py_ssize_t len) { Py_hash_t x; /* We make the hash of the empty string be 0, rather than using (prefix ^ suffix), since this slightly obfuscates the hash secret */ if (len == 0) { return 0; } #ifdef Py_HASH_STATS hashstats[(len <= Py_HASH_STATS_MAX) ? len : 0]++; #endif #if Py_HASH_CUTOFF > 0 if (len < Py_HASH_CUTOFF) { /* Optimize hashing of very small strings with inline DJBX33A. */ Py_uhash_t hash; const unsigned char *p = src; hash = 5381; /* DJBX33A starts with 5381 */ switch(len) { /* ((hash << 5) + hash) + *p == hash * 33 + *p */ case 7: hash = ((hash << 5) + hash) + *p++; /* fallthrough */ case 6: hash = ((hash << 5) + hash) + *p++; /* fallthrough */ case 5: hash = ((hash << 5) + hash) + *p++; /* fallthrough */ case 4: hash = ((hash << 5) + hash) + *p++; /* fallthrough */ case 3: hash = ((hash << 5) + hash) + *p++; /* fallthrough */ case 2: hash = ((hash << 5) + hash) + *p++; /* fallthrough */ case 1: hash = ((hash << 5) + hash) + *p++; break; default: assert(0); } hash ^= len; hash ^= (Py_uhash_t) _Py_HashSecret.djbx33a.suffix; x = (Py_hash_t)hash; } else #endif /* Py_HASH_CUTOFF */ x = PyHash_Func.hash(src, len); if (x == -1) return -2; return x; } void _PyHash_Fini(void) { #ifdef Py_HASH_STATS int i; Py_ssize_t total = 0; char *fmt = "%2i %8" PY_FORMAT_SIZE_T "d %8" PY_FORMAT_SIZE_T "d\n"; fprintf(stderr, "len calls total\n"); for (i = 1; i <= Py_HASH_STATS_MAX; i++) { total += hashstats[i]; fprintf(stderr, fmt, i, hashstats[i], total); } total += hashstats[0]; fprintf(stderr, "> %8" PY_FORMAT_SIZE_T "d %8" PY_FORMAT_SIZE_T "d\n", hashstats[0], total); #endif } PyHash_FuncDef * PyHash_GetFuncDef(void) { return &PyHash_Func; } /* Optimized memcpy() for Windows */ #ifdef _MSC_VER # if SIZEOF_PY_UHASH_T == 4 # define PY_UHASH_CPY(dst, src) do { \ dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; \ } while(0) # elif SIZEOF_PY_UHASH_T == 8 # define PY_UHASH_CPY(dst, src) do { \ dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; \ dst[4] = src[4]; dst[5] = src[5]; dst[6] = src[6]; dst[7] = src[7]; \ } while(0) # else # error SIZEOF_PY_UHASH_T must be 4 or 8 # endif /* SIZEOF_PY_UHASH_T */ #else /* not Windows */ # define PY_UHASH_CPY(dst, src) memcpy(dst, src, SIZEOF_PY_UHASH_T) #endif /* _MSC_VER */ #if Py_HASH_ALGORITHM == Py_HASH_FNV /* ************************************************************************** * Modified Fowler-Noll-Vo (FNV) hash function */ static Py_hash_t fnv(const void *src, Py_ssize_t len) { const unsigned char *p = src; Py_uhash_t x; Py_ssize_t remainder, blocks; union { Py_uhash_t value; unsigned char bytes[SIZEOF_PY_UHASH_T]; } block; #ifdef Py_DEBUG assert(_Py_HashSecret_Initialized); #endif remainder = len % SIZEOF_PY_UHASH_T; if (remainder == 0) { /* Process at least one block byte by byte to reduce hash collisions * for strings with common prefixes. */ remainder = SIZEOF_PY_UHASH_T; } blocks = (len - remainder) / SIZEOF_PY_UHASH_T; x = (Py_uhash_t) _Py_HashSecret.fnv.prefix; x ^= (Py_uhash_t) *p << 7; while (blocks--) { PY_UHASH_CPY(block.bytes, p); x = (_PyHASH_MULTIPLIER * x) ^ block.value; p += SIZEOF_PY_UHASH_T; } /* add remainder */ for (; remainder > 0; remainder--) x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *p++; x ^= (Py_uhash_t) len; x ^= (Py_uhash_t) _Py_HashSecret.fnv.suffix; if (x == (Py_uhash_t) -1) { x = (Py_uhash_t) -2; } return x; } static PyHash_FuncDef PyHash_Func = {fnv, "fnv", 8 * SIZEOF_PY_HASH_T, 16 * SIZEOF_PY_HASH_T}; #endif /* Py_HASH_ALGORITHM == Py_HASH_FNV */ #if Py_HASH_ALGORITHM == Py_HASH_SIPHASH24 /* ************************************************************************** <MIT License> Copyright (c) 2013 Marek Majkowski <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. </MIT License> Original location: https://github.com/majek/csiphash/ Solution inspired by code from: Samuel Neves (supercop/crypto_auth/siphash24/little) djb (supercop/crypto_auth/siphash24/little2) Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c) Modified for Python by Christian Heimes: - C89 / MSVC compatibility - _rotl64() on Windows - letoh64() fallback */ /* byte swap little endian to host endian * Endian conversion not only ensures that the hash function returns the same * value on all platforms. It is also required to for a good dispersion of * the hash values' least significant bits. */ #if PY_LITTLE_ENDIAN # define _le64toh(x) ((uint64_t)(x)) #elif defined(__APPLE__) # define _le64toh(x) OSSwapLittleToHostInt64(x) #elif defined(HAVE_LETOH64) # define _le64toh(x) le64toh(x) #else # define _le64toh(x) (((uint64_t)(x) << 56) | \ (((uint64_t)(x) << 40) & 0xff000000000000ULL) | \ (((uint64_t)(x) << 24) & 0xff0000000000ULL) | \ (((uint64_t)(x) << 8) & 0xff00000000ULL) | \ (((uint64_t)(x) >> 8) & 0xff000000ULL) | \ (((uint64_t)(x) >> 24) & 0xff0000ULL) | \ (((uint64_t)(x) >> 40) & 0xff00ULL) | \ ((uint64_t)(x) >> 56)) #endif #ifdef _MSC_VER # define ROTATE(x, b) _rotl64(x, b) #else # define ROTATE(x, b) (uint64_t)( ((x) << (b)) | ( (x) >> (64 - (b))) ) #endif #define HALF_ROUND(a,b,c,d,s,t) \ a += b; c += d; \ b = ROTATE(b, s) ^ a; \ d = ROTATE(d, t) ^ c; \ a = ROTATE(a, 32); #define DOUBLE_ROUND(v0,v1,v2,v3) \ HALF_ROUND(v0,v1,v2,v3,13,16); \ HALF_ROUND(v2,v1,v0,v3,17,21); \ HALF_ROUND(v0,v1,v2,v3,13,16); \ HALF_ROUND(v2,v1,v0,v3,17,21); static Py_hash_t siphash24(const void *src, Py_ssize_t src_sz) { uint64_t k0 = _le64toh(_Py_HashSecret.siphash.k0); uint64_t k1 = _le64toh(_Py_HashSecret.siphash.k1); uint64_t b = (uint64_t)src_sz << 56; const uint8_t *in = (uint8_t*)src; uint64_t v0 = k0 ^ 0x736f6d6570736575ULL; uint64_t v1 = k1 ^ 0x646f72616e646f6dULL; uint64_t v2 = k0 ^ 0x6c7967656e657261ULL; uint64_t v3 = k1 ^ 0x7465646279746573ULL; uint64_t t; uint8_t *pt; while (src_sz >= 8) { uint64_t mi; memcpy(&mi, in, sizeof(mi)); mi = _le64toh(mi); in += sizeof(mi); src_sz -= sizeof(mi); v3 ^= mi; DOUBLE_ROUND(v0,v1,v2,v3); v0 ^= mi; } t = 0; pt = (uint8_t *)&t; switch (src_sz) { case 7: pt[6] = in[6]; /* fall through */ case 6: pt[5] = in[5]; /* fall through */ case 5: pt[4] = in[4]; /* fall through */ case 4: memcpy(pt, in, sizeof(uint32_t)); break; case 3: pt[2] = in[2]; /* fall through */ case 2: pt[1] = in[1]; /* fall through */ case 1: pt[0] = in[0]; /* fall through */ } b |= _le64toh(t); v3 ^= b; DOUBLE_ROUND(v0,v1,v2,v3); v0 ^= b; v2 ^= 0xff; DOUBLE_ROUND(v0,v1,v2,v3); DOUBLE_ROUND(v0,v1,v2,v3); /* modified */ t = (v0 ^ v1) ^ (v2 ^ v3); return (Py_hash_t)t; } static PyHash_FuncDef PyHash_Func = {siphash24, "siphash24", 64, 128}; #endif /* Py_HASH_ALGORITHM == Py_HASH_SIPHASH24 */
13,945
417
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/cosmomodule.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #define PY_SSIZE_T_CLEAN #include "dsp/scale/cdecimate2xuint8x8.h" #include "libc/calls/calls.h" #include "libc/calls/pledge.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/popcnt.h" #include "libc/macros.internal.h" #include "libc/math.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/crc32.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/nexgen32e/rdtscp.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/methodobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/moduleobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pyport.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/yoink.h" #include "third_party/xed/x86.h" /* clang-format off */ PYTHON_PROVIDE("cosmo"); PYTHON_PROVIDE("cosmo.exit1"); PYTHON_PROVIDE("cosmo.rdtsc"); PYTHON_PROVIDE("cosmo.crc32c"); PYTHON_PROVIDE("cosmo.syscount"); PYTHON_PROVIDE("cosmo.popcount"); PYTHON_PROVIDE("cosmo.decimate"); PYTHON_PROVIDE("cosmo.ftrace"); #ifdef __x86_64__ PYTHON_PROVIDE("cosmo.getcpucore"); PYTHON_PROVIDE("cosmo.getcpunode"); #endif /* __x86_64__ */ PyDoc_STRVAR(cosmo_doc, "Cosmopolitan Libc Module\n\ \n\ This module exposes low-level utilities from the Cosmopolitan library.\n\ \n\ Static objects:\n\ \n\ MODE -- make build mode, e.g. \"\", \"tiny\", \"opt\", \"rel\", etc.\n\ IMAGE_BASE_VIRTUAL -- base address of actually portable executable image\n\ kernel -- o/s platform, e.g. \"linux\", \"xnu\", \"metal\", \"nt\", etc.\n\ kStartTsc -- the rdtsc() value at process creation."); PyDoc_STRVAR(syscount_doc, "syscount($module)\n\ --\n\n\ Returns number of SYSCALL instructions issued to kernel by C library.\n\ \n\ Context switching from userspace to kernelspace is expensive! So it is\n\ useful to be able to know how many times that's happening in your app.\n\ \n\ This value currently isn't meaningful on Windows NT, where it currently\n\ tracks the number of POSIX calls that were attempted, but have not been\n\ polyfilled yet."); static PyObject * cosmo_syscount(PyObject *self, PyObject *noargs) { return PyLong_FromSize_t(__syscount); } PyDoc_STRVAR(rdtsc_doc, "rdtsc($module)\n\ --\n\n\ Returns CPU timestamp counter."); static PyObject * cosmo_rdtsc(PyObject *self, PyObject *noargs) { return PyLong_FromUnsignedLong(rdtsc()); } PyDoc_STRVAR(getcpucore_doc, "getcpucore($module)\n\ --\n\n\ Returns 0-indexed CPU core on which process is currently scheduled."); #ifdef __x86_64__ static PyObject * cosmo_getcpucore(PyObject *self, PyObject *noargs) { return PyLong_FromUnsignedLong(TSC_AUX_CORE(rdpid())); } PyDoc_STRVAR(getcpunode_doc, "getcpunode($module)\n\ --\n\n\ Returns 0-indexed NUMA node on which process is currently scheduled."); static PyObject * cosmo_getcpunode(PyObject *self, PyObject *noargs) { return PyLong_FromUnsignedLong(TSC_AUX_NODE(rdpid())); } #endif /* __x86_64__ */ PyDoc_STRVAR(crc32c_doc, "crc32c($module, bytes, init=0)\n\ --\n\n\ Computes 32-bit Castagnoli Cyclic Redundancy Check.\n\ \n\ Used by ISCSI, TensorFlow, etc.\n\ Similar to zlib.crc32()."); static PyObject * cosmo_crc32c(PyObject *self, PyObject *args) { Py_ssize_t n; Py_buffer data; unsigned crc, init = 0; if (!PyArg_ParseTuple(args, "y*|I:crc32c", &data, &init)) return 0; crc = crc32c(init, data.buf, data.len); PyBuffer_Release(&data); return PyLong_FromUnsignedLong(crc); } PyDoc_STRVAR(decimate_doc, "decimate($module, bytes)\n\ --\n\n\ Shrinks byte buffer in half using John Costella's magic kernel.\n\ \n\ This downscales data 2x using an eight-tap convolution, e.g.\n\ \n\ >>> cosmo.decimate(b'\\xff\\xff\\x00\\x00\\xff\\xff\\x00\\x00\\xff\\xff\\x00\\x00')\n\ b'\\xff\\x00\\xff\\x00\\xff\\x00'\n\ \n\ This is very fast if SSSE3 is available (Intel 2004+ / AMD 2011+)."); static PyObject * cosmo_decimate(PyObject *self, PyObject *args) { Py_ssize_t n; PyObject *buf; Py_buffer data; if (!PyArg_ParseTuple(args, "y*:decimate", &data)) return 0; if ((buf = PyBytes_FromStringAndSize(0, (n = ROUNDUP(data.len, 16))))) { memcpy(PyBytes_AS_STRING(buf), data.buf, data.len); memset(PyBytes_AS_STRING(buf) + data.len, 0, n - data.len); cDecimate2xUint8x8(n, (void *)PyBytes_AS_STRING(buf), (signed char[8]){-1, -3, 3, 17, 17, 3, -3, -1}); _PyBytes_Resize(&buf, (data.len + 1) >> 1); } PyBuffer_Release(&data); return buf; } PyDoc_STRVAR(popcount_doc, "popcount($module, bytes)\n\ --\n\n\ Returns population count of byte sequence, e.g.\n\ \n\ >>> cosmo.popcount(b'\\xff\\x00\\xff')\n\ 16\n\ \n\ The population count is the number of bits that are set to one.\n\ It does the same thing as `Long.bit_count()` but for data buffers.\n\ This goes 30gbps on Nehalem (Intel 2008+) so it's quite fast."); static PyObject * cosmo_popcount(PyObject *self, PyObject *args) { Py_ssize_t n; const char *p; if (!PyArg_ParseTuple(args, "y#:popcount", &p, &n)) return 0; return PyLong_FromSize_t(_countbits(p, n)); } PyDoc_STRVAR(pledge_doc, "pledge($module, promises, execpromises)\n\ --\n\n\ Permits syscall operations, e.g.\n\ \n\ >>> cosmo.pledge('stdio rpath tty', None)\n\ \n\ This function implements the OpenBSD pledge() API for\n\ OpenBSD and Linux, where we use SECCOMP BPF. Read the\n\ Cosmopolitan Libc documentation to learn more."); static PyObject * cosmo_pledge(PyObject *self, PyObject *args) { int e = errno; const char *x, *y; if (!PyArg_ParseTuple(args, "sz:pledge", &x, &y)) return 0; __pledge_mode = PLEDGE_PENALTY_RETURN_EPERM; if (!pledge(x, y)) { Py_RETURN_NONE; } else { PyErr_SetString(PyExc_SystemError, strerror(errno)); errno = e; return 0; } } PyDoc_STRVAR(unveil_doc, "unveil($module, path, permissions)\n\ --\n\n\ Permits filesystem operations, e.g.\n\ \n\ >>> cosmo.unveil('.', 'rwcx')\n\ >>> cosmo.unveil(None, None)\n\ \n\ This function implements the OpenBSD unveil() API for\n\ OpenBSD and Linux where we use Landlock LSM. Read the\n\ Cosmopolitan Libc documentation to learn more."); static PyObject * cosmo_unveil(PyObject *self, PyObject *args) { int e = errno; const char *x, *y; if (!PyArg_ParseTuple(args, "zz:unveil", &x, &y)) return 0; if (!unveil(x, y)) { Py_RETURN_NONE; } else { PyErr_SetString(PyExc_SystemError, strerror(errno)); errno = e; return 0; } } PyDoc_STRVAR(exit1_doc, "exit1($module)\n\ --\n\n\ Calls _Exit(1).\n\ \n\ This function is intended to abruptly end the process with less\n\ function trace output compared to os._exit(1)."); static PyObject * cosmo_exit1(PyObject *self, PyObject *args) { _Exit(1); } static bool ftrace_installed = 0; typedef struct { PyObject_HEAD } FtracerObject; static int FtracerObject_init(PyObject* self, PyObject *args, PyObject *kwargs) { ftrace_install(); return 0; } static PyObject* FtracerObject_enter(PyObject *self, PyObject *Py_UNUSED(ignored)) { ftrace_enabled(+1); return self; } static PyObject* FtracerObject_exit(PyObject *self, PyObject *args) { ftrace_enabled(-1); return self; } static PyMethodDef FtracerObject_methods[] = { {"__enter__", (PyCFunction) FtracerObject_enter, METH_NOARGS, "enables c function call logging"}, {"__exit__", (PyCFunction) FtracerObject_exit, METH_VARARGS, "disables c function call logging"}, {0} }; static PyTypeObject FtracerType = { PyVarObject_HEAD_INIT(NULL, 0) .tp_name = "cosmo.Ftracer", .tp_doc = "wrapping ftrace with a context manager", .tp_basicsize = sizeof(FtracerObject), .tp_itemsize = 0, .tp_flags = Py_TPFLAGS_DEFAULT, .tp_new = PyType_GenericNew, .tp_init = (initproc) FtracerObject_init, .tp_methods = FtracerObject_methods, }; PyDoc_STRVAR(ftrace_doc, "ftrace($module)\n\ --\n\n\ Enables logging of C function calls to stderr, e.g.\n\ \n\ with cosmo.ftrace() as F:\n\ WeirdFunction()\n\ \n\ Please be warned this prints massive amount of text. In order for it\n\ to work, the concomitant .com.dbg binary needs to be present."); static PyObject * cosmo_ftrace(PyObject *self, PyObject *noargs) { PyObject *tracer = PyType_GenericNew(&FtracerType, NULL, NULL); if (tracer == NULL) Py_RETURN_NONE; FtracerObject_init(tracer, NULL, NULL); return tracer; } static PyMethodDef cosmo_methods[] = { {"exit1", cosmo_exit1, METH_NOARGS, exit1_doc}, {"rdtsc", cosmo_rdtsc, METH_NOARGS, rdtsc_doc}, {"crc32c", cosmo_crc32c, METH_VARARGS, crc32c_doc}, {"pledge", cosmo_pledge, METH_VARARGS, pledge_doc}, {"unveil", cosmo_unveil, METH_VARARGS, unveil_doc}, {"syscount", cosmo_syscount, METH_NOARGS, syscount_doc}, {"popcount", cosmo_popcount, METH_VARARGS, popcount_doc}, {"decimate", cosmo_decimate, METH_VARARGS, decimate_doc}, #ifdef __x86_64__ {"getcpucore", cosmo_getcpucore, METH_NOARGS, getcpucore_doc}, {"getcpunode", cosmo_getcpunode, METH_NOARGS, getcpunode_doc}, #endif /* __x86_64__ */ #ifdef __PG__ {"ftrace", cosmo_ftrace, METH_NOARGS, ftrace_doc}, #endif {0}, }; static struct PyModuleDef cosmomodule = { PyModuleDef_HEAD_INIT, "cosmo", cosmo_doc, -1, cosmo_methods, }; static const char * GetKernelName(void) { if (IsLinux()) { return "linux"; } else if (IsXnu()) { return "xnu"; } else if (IsMetal()) { return "metal"; } else if (IsWindows()) { return "nt"; } else if (IsFreebsd()) { return "freebsd"; } else if (IsOpenbsd()) { return "openbsd"; } else if (IsNetbsd()) { return "netbsd"; } else { return "wut"; } } PyMODINIT_FUNC PyInit_cosmo(void) { PyObject *m; if (PyType_Ready(&FtracerType) < 0) return 0; if (!(m = PyModule_Create(&cosmomodule))) return 0; PyModule_AddStringConstant(m, "MODE", MODE); PyModule_AddIntConstant(m, "IMAGE_BASE_VIRTUAL", IMAGE_BASE_VIRTUAL); PyModule_AddStringConstant(m, "kernel", GetKernelName()); PyModule_AddIntConstant(m, "kStartTsc", kStartTsc); Py_INCREF(&FtracerType); // PyModule_AddObject(m, "Tracer", (PyObject *) &TracerType); return !PyErr_Occurred() ? m : 0; } _Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_cosmo = { "cosmo", PyInit_cosmo, };
12,598
400
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/getsig.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/calls/struct/sigaction.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/pyconfig.h" /* clang-format off */ PyOS_sighandler_t PyOS_getsig(int sig) { #ifdef HAVE_SIGACTION struct sigaction context; if (sigaction(sig, NULL, &context) == -1) return SIG_ERR; return context.sa_handler; #else PyOS_sighandler_t handler; /* Special signal handling for the secure CRT in Visual Studio 2005 */ #if defined(_MSC_VER) && _MSC_VER >= 1400 switch (sig) { /* Only these signals are valid */ case SIGINT: case SIGILL: case SIGFPE: case SIGSEGV: case SIGTERM: case SIGBREAK: case SIGABRT: break; /* Don't call signal() with other values or it will assert */ default: return SIG_ERR; } #endif /* _MSC_VER && _MSC_VER >= 1400 */ handler = signal(sig, SIG_IGN); if (handler != SIG_ERR) signal(sig, handler); return handler; #endif } /* * All of the code in this function must only use async-signal-safe functions, * listed at `man 7 signal` or * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html. */ PyOS_sighandler_t PyOS_setsig(int sig, PyOS_sighandler_t handler) { #ifdef HAVE_SIGACTION /* Some code in Modules/signalmodule.c depends on sigaction() being * used here if HAVE_SIGACTION is defined. Fix that if this code * changes to invalidate that assumption. */ struct sigaction context, ocontext; context.sa_handler = handler; sigemptyset(&context.sa_mask); context.sa_flags = 0; if (sigaction(sig, &context, &ocontext) == -1) return SIG_ERR; return ocontext.sa_handler; #else PyOS_sighandler_t oldhandler; oldhandler = signal(sig, handler); #ifdef HAVE_SIGINTERRUPT siginterrupt(sig, 1); #endif return oldhandler; #endif }
2,761
77
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/restoresigs.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/sysv/consts/sig.h" #include "third_party/python/Include/pylifecycle.h" /* clang-format off */ /* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL. * * All of the code in this function must only use async-signal-safe functions, * listed at `man 7 signal` or * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html. */ void _Py_RestoreSignals(void) { #ifdef SIGPIPE PyOS_setsig(SIGPIPE, SIG_DFL); #endif #ifdef SIGXFZ PyOS_setsig(SIGXFZ, SIG_DFL); #endif #ifdef SIGXFSZ PyOS_setsig(SIGXFSZ, SIG_DFL); #endif }
1,429
31
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/modsupport.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/tupleobject.h" /* clang-format off */ #define FLAG_SIZE_T 1 typedef double va_double; static PyObject *va_build_value(const char *, va_list, int); static PyObject **va_build_stack(PyObject **small_stack, Py_ssize_t small_stack_len, const char *, va_list, int, Py_ssize_t*); /* Package context -- the full module name for package imports */ const char *_Py_PackageContext = NULL; /* Helper for mkvalue() to scan the length of a format */ static Py_ssize_t countformat(const char *format, char endchar) { Py_ssize_t count = 0; int level = 0; while (level > 0 || *format != endchar) { switch (*format) { case '\0': /* Premature end */ PyErr_SetString(PyExc_SystemError, "unmatched paren in format"); return -1; case '(': case '[': case '{': if (level == 0) { count++; } level++; break; case ')': case ']': case '}': level--; break; case '#': case '&': case ',': case ':': case ' ': case '\t': break; default: if (level == 0) { count++; } } format++; } return count; } /* Generic function to create a value -- the inverse of getargs() */ /* After an original idea and first implementation by Steven Miale */ static PyObject *do_mktuple(const char**, va_list *, char, Py_ssize_t, int); static int do_mkstack(PyObject **, const char**, va_list *, char, Py_ssize_t, int); static PyObject *do_mklist(const char**, va_list *, char, Py_ssize_t, int); static PyObject *do_mkdict(const char**, va_list *, char, Py_ssize_t, int); static PyObject *do_mkvalue(const char**, va_list *, int); static void do_ignore(const char **p_format, va_list *p_va, char endchar, Py_ssize_t n, int flags) { PyObject *v; Py_ssize_t i; assert(PyErr_Occurred()); v = PyTuple_New(n); for (i = 0; i < n; i++) { PyObject *exception, *value, *tb, *w; PyErr_Fetch(&exception, &value, &tb); w = do_mkvalue(p_format, p_va, flags); PyErr_Restore(exception, value, tb); if (w != NULL) { if (v != NULL) { PyTuple_SET_ITEM(v, i, w); } else { Py_DECREF(w); } } } Py_XDECREF(v); if (**p_format != endchar) { PyErr_SetString(PyExc_SystemError, "Unmatched paren in format"); return; } if (endchar) { ++*p_format; } } static PyObject * do_mkdict(const char **p_format, va_list *p_va, char endchar, Py_ssize_t n, int flags) { PyObject *d; Py_ssize_t i; if (n < 0) return NULL; if (n % 2) { PyErr_SetString(PyExc_SystemError, "Bad dict format"); do_ignore(p_format, p_va, endchar, n, flags); return NULL; } /* Note that we can't bail immediately on error as this will leak refcounts on any 'N' arguments. */ if ((d = PyDict_New()) == NULL) { do_ignore(p_format, p_va, endchar, n, flags); return NULL; } for (i = 0; i < n; i+= 2) { PyObject *k, *v; k = do_mkvalue(p_format, p_va, flags); if (k == NULL) { do_ignore(p_format, p_va, endchar, n - i - 1, flags); Py_DECREF(d); return NULL; } v = do_mkvalue(p_format, p_va, flags); if (v == NULL || PyDict_SetItem(d, k, v) < 0) { do_ignore(p_format, p_va, endchar, n - i - 2, flags); Py_DECREF(k); Py_XDECREF(v); Py_DECREF(d); return NULL; } Py_DECREF(k); Py_DECREF(v); } if (**p_format != endchar) { Py_DECREF(d); PyErr_SetString(PyExc_SystemError, "Unmatched paren in format"); return NULL; } if (endchar) ++*p_format; return d; } static PyObject * do_mklist(const char **p_format, va_list *p_va, char endchar, Py_ssize_t n, int flags) { PyObject *v; Py_ssize_t i; if (n < 0) return NULL; /* Note that we can't bail immediately on error as this will leak refcounts on any 'N' arguments. */ v = PyList_New(n); if (v == NULL) { do_ignore(p_format, p_va, endchar, n, flags); return NULL; } for (i = 0; i < n; i++) { PyObject *w = do_mkvalue(p_format, p_va, flags); if (w == NULL) { do_ignore(p_format, p_va, endchar, n - i - 1, flags); Py_DECREF(v); return NULL; } PyList_SET_ITEM(v, i, w); } if (**p_format != endchar) { Py_DECREF(v); PyErr_SetString(PyExc_SystemError, "Unmatched paren in format"); return NULL; } if (endchar) ++*p_format; return v; } static int do_mkstack(PyObject **stack, const char **p_format, va_list *p_va, char endchar, Py_ssize_t n, int flags) { Py_ssize_t i; if (n < 0) { return -1; } /* Note that we can't bail immediately on error as this will leak refcounts on any 'N' arguments. */ for (i = 0; i < n; i++) { PyObject *w = do_mkvalue(p_format, p_va, flags); if (w == NULL) { do_ignore(p_format, p_va, endchar, n - i - 1, flags); goto error; } stack[i] = w; } if (**p_format != endchar) { PyErr_SetString(PyExc_SystemError, "Unmatched paren in format"); goto error; } if (endchar) { ++*p_format; } return 0; error: n = i; for (i=0; i < n; i++) { Py_DECREF(stack[i]); } return -1; } static PyObject * do_mktuple(const char **p_format, va_list *p_va, char endchar, Py_ssize_t n, int flags) { PyObject *v; Py_ssize_t i; if (n < 0) return NULL; /* Note that we can't bail immediately on error as this will leak refcounts on any 'N' arguments. */ if ((v = PyTuple_New(n)) == NULL) { do_ignore(p_format, p_va, endchar, n, flags); return NULL; } for (i = 0; i < n; i++) { PyObject *w = do_mkvalue(p_format, p_va, flags); if (w == NULL) { do_ignore(p_format, p_va, endchar, n - i - 1, flags); Py_DECREF(v); return NULL; } PyTuple_SET_ITEM(v, i, w); } if (**p_format != endchar) { Py_DECREF(v); PyErr_SetString(PyExc_SystemError, "Unmatched paren in format"); return NULL; } if (endchar) ++*p_format; return v; } static PyObject * do_mkvalue(const char **p_format, va_list *p_va, int flags) { for (;;) { switch (*(*p_format)++) { case '(': return do_mktuple(p_format, p_va, ')', countformat(*p_format, ')'), flags); case '[': return do_mklist(p_format, p_va, ']', countformat(*p_format, ']'), flags); case '{': return do_mkdict(p_format, p_va, '}', countformat(*p_format, '}'), flags); case 'b': case 'B': case 'h': case 'i': return PyLong_FromLong((long)va_arg(*p_va, int)); case 'H': return PyLong_FromLong((long)va_arg(*p_va, unsigned int)); case 'I': { unsigned int n; n = va_arg(*p_va, unsigned int); return PyLong_FromUnsignedLong(n); } case 'n': #if SIZEOF_SIZE_T!=SIZEOF_LONG return PyLong_FromSsize_t(va_arg(*p_va, Py_ssize_t)); #endif /* Fall through from 'n' to 'l' if Py_ssize_t is long */ case 'l': return PyLong_FromLong(va_arg(*p_va, long)); case 'k': { unsigned long n; n = va_arg(*p_va, unsigned long); return PyLong_FromUnsignedLong(n); } case 'L': return PyLong_FromLongLong((long long)va_arg(*p_va, long long)); case 'K': return PyLong_FromUnsignedLongLong((long long)va_arg(*p_va, unsigned long long)); case 'u': { PyObject *v; Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *); Py_ssize_t n; if (**p_format == '#') { ++*p_format; if (flags & FLAG_SIZE_T) n = va_arg(*p_va, Py_ssize_t); else n = va_arg(*p_va, int); } else n = -1; if (u == NULL) { v = Py_None; Py_INCREF(v); } else { if (n < 0) n = wcslen(u); v = PyUnicode_FromWideChar(u, n); } return v; } case 'f': case 'd': return PyFloat_FromDouble( (double)va_arg(*p_va, va_double)); case 'D': return PyComplex_FromCComplex( *((Py_complex *)va_arg(*p_va, Py_complex *))); case 'c': { char p[1]; p[0] = (char)va_arg(*p_va, int); return PyBytes_FromStringAndSize(p, 1); } case 'C': { int i = va_arg(*p_va, int); return PyUnicode_FromOrdinal(i); } case 's': case 'z': case 'U': /* XXX deprecated alias */ { PyObject *v; const char *str = va_arg(*p_va, const char *); Py_ssize_t n; if (**p_format == '#') { ++*p_format; if (flags & FLAG_SIZE_T) n = va_arg(*p_va, Py_ssize_t); else n = va_arg(*p_va, int); } else n = -1; if (str == NULL) { v = Py_None; Py_INCREF(v); } else { if (n < 0) { size_t m = strlen(str); if (m > PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "string too long for Python string"); return NULL; } n = (Py_ssize_t)m; } v = PyUnicode_FromStringAndSize(str, n); } return v; } case 'y': { PyObject *v; const char *str = va_arg(*p_va, const char *); Py_ssize_t n; if (**p_format == '#') { ++*p_format; if (flags & FLAG_SIZE_T) n = va_arg(*p_va, Py_ssize_t); else n = va_arg(*p_va, int); } else n = -1; if (str == NULL) { v = Py_None; Py_INCREF(v); } else { if (n < 0) { size_t m = strlen(str); if (m > PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "string too long for Python bytes"); return NULL; } n = (Py_ssize_t)m; } v = PyBytes_FromStringAndSize(str, n); } return v; } case 'N': case 'S': case 'O': if (**p_format == '&') { typedef PyObject *(*converter)(void *); converter func = va_arg(*p_va, converter); void *arg = va_arg(*p_va, void *); ++*p_format; return (*func)(arg); } else { PyObject *v; v = va_arg(*p_va, PyObject *); if (v != NULL) { if (*(*p_format - 1) != 'N') Py_INCREF(v); } else if (!PyErr_Occurred()) /* If a NULL was passed * because a call that should * have constructed a value * failed, that's OK, and we * pass the error on; but if * no error occurred it's not * clear that the caller knew * what she was doing. */ PyErr_SetString(PyExc_SystemError, "NULL object passed to Py_BuildValue"); return v; } case ':': case ',': case ' ': case '\t': break; default: PyErr_SetString(PyExc_SystemError, "bad format char passed to Py_BuildValue"); return NULL; } } } PyObject * Py_BuildValue(const char *format, ...) { va_list va; PyObject* retval; va_start(va, format); retval = va_build_value(format, va, 0); va_end(va); return retval; } PyObject * _Py_BuildValue_SizeT(const char *format, ...) { va_list va; PyObject* retval; va_start(va, format); retval = va_build_value(format, va, FLAG_SIZE_T); va_end(va); return retval; } PyObject * Py_VaBuildValue(const char *format, va_list va) { return va_build_value(format, va, 0); } PyObject * _Py_VaBuildValue_SizeT(const char *format, va_list va) { return va_build_value(format, va, FLAG_SIZE_T); } static PyObject * va_build_value(const char *format, va_list va, int flags) { const char *f = format; Py_ssize_t n = countformat(f, '\0'); va_list lva; PyObject *retval; if (n < 0) return NULL; if (n == 0) { Py_INCREF(Py_None); return Py_None; } va_copy(lva, va); if (n == 1) { retval = do_mkvalue(&f, &lva, flags); } else { retval = do_mktuple(&f, &lva, '\0', n, flags); } va_end(lva); return retval; } PyObject ** _Py_VaBuildStack(PyObject **small_stack, Py_ssize_t small_stack_len, const char *format, va_list va, Py_ssize_t *p_nargs) { return va_build_stack(small_stack, small_stack_len, format, va, 0, p_nargs); } PyObject ** _Py_VaBuildStack_SizeT(PyObject **small_stack, Py_ssize_t small_stack_len, const char *format, va_list va, Py_ssize_t *p_nargs) { return va_build_stack(small_stack, small_stack_len, format, va, FLAG_SIZE_T, p_nargs); } static PyObject ** va_build_stack(PyObject **small_stack, Py_ssize_t small_stack_len, const char *format, va_list va, int flags, Py_ssize_t *p_nargs) { const char *f; Py_ssize_t n; va_list lva; PyObject **stack; int res; n = countformat(format, '\0'); if (n < 0) { *p_nargs = 0; return NULL; } if (n == 0) { *p_nargs = 0; return small_stack; } if (n <= small_stack_len) { stack = small_stack; } else { stack = PyMem_Malloc(n * sizeof(stack[0])); if (stack == NULL) { PyErr_NoMemory(); return NULL; } } va_copy(lva, va); f = format; res = do_mkstack(stack, &f, &lva, '\0', n, flags); va_end(lva); if (res < 0) { return NULL; } *p_nargs = n; return stack; } int PyModule_AddObject(PyObject *m, const char *name, PyObject *o) { PyObject *dict; if (!PyModule_Check(m)) { PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs module as first arg"); return -1; } if (!o) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "PyModule_AddObject() needs non-NULL value"); return -1; } dict = PyModule_GetDict(m); if (dict == NULL) { /* Internal error -- modules must have a dict! */ PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__", PyModule_GetName(m)); return -1; } if (PyDict_SetItemString(dict, name, o)) return -1; Py_DECREF(o); return 0; } int PyModule_AddIntConstant(PyObject *m, const char *name, long value) { PyObject *o = PyLong_FromLong(value); if (!o) return -1; if (PyModule_AddObject(m, name, o) == 0) return 0; Py_DECREF(o); return -1; } int PyModule_AddStringConstant(PyObject *m, const char *name, const char *value) { PyObject *o = PyUnicode_FromString(value); if (!o) return -1; if (PyModule_AddObject(m, name, o) == 0) return 0; Py_DECREF(o); return -1; }
18,087
655
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/bltinmodule.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/asdl.h" #include "third_party/python/Include/ast.h" #include "third_party/python/Include/bltinmodule.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/bytearrayobject.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/cellobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/compile.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/descrobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/enumobject.h" #include "third_party/python/Include/eval.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/funcobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/iterobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/memoryobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyfpe.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/rangeobject.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/warnings.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ PYTHON_PROVIDE("builtins.ArithmeticError"); PYTHON_PROVIDE("builtins.AssertionError"); PYTHON_PROVIDE("builtins.AttributeError"); PYTHON_PROVIDE("builtins.BaseException"); PYTHON_PROVIDE("builtins.BlockingIOError"); PYTHON_PROVIDE("builtins.BrokenPipeError"); PYTHON_PROVIDE("builtins.BufferError"); PYTHON_PROVIDE("builtins.BytesWarning"); PYTHON_PROVIDE("builtins.ChildProcessError"); PYTHON_PROVIDE("builtins.ConnectionAbortedError"); PYTHON_PROVIDE("builtins.ConnectionError"); PYTHON_PROVIDE("builtins.ConnectionRefusedError"); PYTHON_PROVIDE("builtins.ConnectionResetError"); PYTHON_PROVIDE("builtins.DeprecationWarning"); PYTHON_PROVIDE("builtins.EOFError"); PYTHON_PROVIDE("builtins.Ellipsis"); PYTHON_PROVIDE("builtins.EnvironmentError"); PYTHON_PROVIDE("builtins.Exception"); PYTHON_PROVIDE("builtins.False"); PYTHON_PROVIDE("builtins.FileExistsError"); PYTHON_PROVIDE("builtins.FileNotFoundError"); PYTHON_PROVIDE("builtins.FloatingPointError"); PYTHON_PROVIDE("builtins.FutureWarning"); PYTHON_PROVIDE("builtins.GeneratorExit"); PYTHON_PROVIDE("builtins.IOError"); PYTHON_PROVIDE("builtins.ImportError"); PYTHON_PROVIDE("builtins.ImportWarning"); PYTHON_PROVIDE("builtins.IndentationError"); PYTHON_PROVIDE("builtins.IndexError"); PYTHON_PROVIDE("builtins.InterruptedError"); PYTHON_PROVIDE("builtins.IsADirectoryError"); PYTHON_PROVIDE("builtins.KeyError"); PYTHON_PROVIDE("builtins.KeyboardInterrupt"); PYTHON_PROVIDE("builtins.LookupError"); PYTHON_PROVIDE("builtins.MemoryError"); PYTHON_PROVIDE("builtins.ModuleNotFoundError"); PYTHON_PROVIDE("builtins.NameError"); PYTHON_PROVIDE("builtins.None"); PYTHON_PROVIDE("builtins.NotADirectoryError"); PYTHON_PROVIDE("builtins.NotImplemented"); PYTHON_PROVIDE("builtins.NotImplementedError"); PYTHON_PROVIDE("builtins.OSError"); PYTHON_PROVIDE("builtins.OverflowError"); PYTHON_PROVIDE("builtins.PendingDeprecationWarning"); PYTHON_PROVIDE("builtins.PermissionError"); PYTHON_PROVIDE("builtins.ProcessLookupError"); PYTHON_PROVIDE("builtins.RecursionError"); PYTHON_PROVIDE("builtins.ReferenceError"); PYTHON_PROVIDE("builtins.ResourceWarning"); PYTHON_PROVIDE("builtins.RuntimeError"); PYTHON_PROVIDE("builtins.RuntimeWarning"); PYTHON_PROVIDE("builtins.StopAsyncIteration"); PYTHON_PROVIDE("builtins.StopIteration"); PYTHON_PROVIDE("builtins.SyntaxError"); PYTHON_PROVIDE("builtins.SyntaxWarning"); PYTHON_PROVIDE("builtins.SystemError"); PYTHON_PROVIDE("builtins.SystemExit"); PYTHON_PROVIDE("builtins.TabError"); PYTHON_PROVIDE("builtins.TimeoutError"); PYTHON_PROVIDE("builtins.True"); PYTHON_PROVIDE("builtins.TypeError"); PYTHON_PROVIDE("builtins.UnboundLocalError"); PYTHON_PROVIDE("builtins.UnicodeDecodeError"); PYTHON_PROVIDE("builtins.UnicodeEncodeError"); PYTHON_PROVIDE("builtins.UnicodeError"); PYTHON_PROVIDE("builtins.UnicodeTranslateError"); PYTHON_PROVIDE("builtins.UnicodeWarning"); PYTHON_PROVIDE("builtins.UserWarning"); PYTHON_PROVIDE("builtins.ValueError"); PYTHON_PROVIDE("builtins.Warning"); PYTHON_PROVIDE("builtins.ZeroDivisionError"); PYTHON_PROVIDE("builtins.__build_class__"); PYTHON_PROVIDE("builtins.__debug__"); PYTHON_PROVIDE("builtins.__doc__"); PYTHON_PROVIDE("builtins.__import__"); PYTHON_PROVIDE("builtins.__loader__"); PYTHON_PROVIDE("builtins.__name__"); PYTHON_PROVIDE("builtins.__package__"); PYTHON_PROVIDE("builtins.__spec__"); PYTHON_PROVIDE("builtins.abs"); PYTHON_PROVIDE("builtins.all"); PYTHON_PROVIDE("builtins.any"); PYTHON_PROVIDE("builtins.ascii"); PYTHON_PROVIDE("builtins.bin"); PYTHON_PROVIDE("builtins.bool"); PYTHON_PROVIDE("builtins.bytearray"); PYTHON_PROVIDE("builtins.bytes"); PYTHON_PROVIDE("builtins.callable"); PYTHON_PROVIDE("builtins.chr"); PYTHON_PROVIDE("builtins.classmethod"); PYTHON_PROVIDE("builtins.compile"); PYTHON_PROVIDE("builtins.complex"); PYTHON_PROVIDE("builtins.copyright"); PYTHON_PROVIDE("builtins.credits"); PYTHON_PROVIDE("builtins.delattr"); PYTHON_PROVIDE("builtins.dict"); PYTHON_PROVIDE("builtins.dir"); PYTHON_PROVIDE("builtins.divmod"); PYTHON_PROVIDE("builtins.enumerate"); PYTHON_PROVIDE("builtins.eval"); PYTHON_PROVIDE("builtins.exec"); PYTHON_PROVIDE("builtins.exit"); PYTHON_PROVIDE("builtins.filter"); PYTHON_PROVIDE("builtins.float"); PYTHON_PROVIDE("builtins.format"); PYTHON_PROVIDE("builtins.frozenset"); PYTHON_PROVIDE("builtins.getattr"); PYTHON_PROVIDE("builtins.globals"); PYTHON_PROVIDE("builtins.hasattr"); PYTHON_PROVIDE("builtins.hash"); PYTHON_PROVIDE("builtins.help"); PYTHON_PROVIDE("builtins.hex"); PYTHON_PROVIDE("builtins.id"); PYTHON_PROVIDE("builtins.input"); PYTHON_PROVIDE("builtins.int"); PYTHON_PROVIDE("builtins.isinstance"); PYTHON_PROVIDE("builtins.issubclass"); PYTHON_PROVIDE("builtins.iter"); PYTHON_PROVIDE("builtins.len"); PYTHON_PROVIDE("builtins.license"); PYTHON_PROVIDE("builtins.list"); PYTHON_PROVIDE("builtins.locals"); PYTHON_PROVIDE("builtins.map"); PYTHON_PROVIDE("builtins.max"); PYTHON_PROVIDE("builtins.memoryview"); PYTHON_PROVIDE("builtins.min"); PYTHON_PROVIDE("builtins.next"); PYTHON_PROVIDE("builtins.object"); PYTHON_PROVIDE("builtins.oct"); PYTHON_PROVIDE("builtins.open"); PYTHON_PROVIDE("builtins.ord"); PYTHON_PROVIDE("builtins.pow"); PYTHON_PROVIDE("builtins.print"); PYTHON_PROVIDE("builtins.property"); PYTHON_PROVIDE("builtins.quit"); PYTHON_PROVIDE("builtins.range"); PYTHON_PROVIDE("builtins.repr"); PYTHON_PROVIDE("builtins.reversed"); PYTHON_PROVIDE("builtins.round"); PYTHON_PROVIDE("builtins.set"); PYTHON_PROVIDE("builtins.setattr"); PYTHON_PROVIDE("builtins.slice"); PYTHON_PROVIDE("builtins.sorted"); PYTHON_PROVIDE("builtins.staticmethod"); PYTHON_PROVIDE("builtins.str"); PYTHON_PROVIDE("builtins.sum"); PYTHON_PROVIDE("builtins.super"); PYTHON_PROVIDE("builtins.tuple"); PYTHON_PROVIDE("builtins.type"); PYTHON_PROVIDE("builtins.vars"); PYTHON_PROVIDE("builtins.zip"); /* Built-in functions */ /* The default encoding used by the platform file system APIs Can remain NULL for all platforms that don't have such a concept Don't forget to modify PyUnicode_DecodeFSDefault() if you touch any of the values for Py_FileSystemDefaultEncoding! */ #if defined(__APPLE__) || defined(__COSMOPOLITAN__) const char *Py_FileSystemDefaultEncoding = "utf-8"; int Py_HasFileSystemDefaultEncoding = 1; #elif defined(MS_WINDOWS) /* may be changed by initfsencoding(), but should never be free()d */ const char *Py_FileSystemDefaultEncoding = "utf-8"; int Py_HasFileSystemDefaultEncoding = 1; #else const char *Py_FileSystemDefaultEncoding = NULL; /* set by initfsencoding() */ int Py_HasFileSystemDefaultEncoding = 0; #endif const char *Py_FileSystemDefaultEncodeErrors = "surrogateescape"; _Py_IDENTIFIER(__builtins__); _Py_IDENTIFIER(__dict__); _Py_IDENTIFIER(__prepare__); _Py_IDENTIFIER(__round__); _Py_IDENTIFIER(encoding); _Py_IDENTIFIER(errors); _Py_IDENTIFIER(fileno); _Py_IDENTIFIER(flush); _Py_IDENTIFIER(metaclass); _Py_IDENTIFIER(sort); _Py_IDENTIFIER(stdin); _Py_IDENTIFIER(stdout); _Py_IDENTIFIER(stderr); #include "third_party/python/Python/clinic/bltinmodule.inc" /* AC: cannot convert yet, waiting for *args support */ static PyObject * builtin___build_class__(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *func, *name, *bases, *mkw, *meta, *winner, *prep, *ns; PyObject *cls = NULL, *cell = NULL; int isclass = 0; /* initialize to prevent gcc warning */ if (nargs < 2) { PyErr_SetString(PyExc_TypeError, "__build_class__: not enough arguments"); return NULL; } func = args[0]; /* Better be callable */ if (!PyFunction_Check(func)) { PyErr_SetString(PyExc_TypeError, "__build_class__: func must be a function"); return NULL; } name = args[1]; if (!PyUnicode_Check(name)) { PyErr_SetString(PyExc_TypeError, "__build_class__: name is not a string"); return NULL; } bases = _PyStack_AsTupleSlice(args, nargs, 2, nargs); if (bases == NULL) return NULL; if (kwnames == NULL) { meta = NULL; mkw = NULL; } else { mkw = _PyStack_AsDict(args + nargs, kwnames); if (mkw == NULL) { Py_DECREF(bases); return NULL; } meta = _PyDict_GetItemId(mkw, &PyId_metaclass); if (meta != NULL) { Py_INCREF(meta); if (_PyDict_DelItemId(mkw, &PyId_metaclass) < 0) { Py_DECREF(meta); Py_DECREF(mkw); Py_DECREF(bases); return NULL; } /* metaclass is explicitly given, check if it's indeed a class */ isclass = PyType_Check(meta); } } if (meta == NULL) { /* if there are no bases, use type: */ if (PyTuple_GET_SIZE(bases) == 0) { meta = (PyObject *) (&PyType_Type); } /* else get the type of the first base */ else { PyObject *base0 = PyTuple_GET_ITEM(bases, 0); meta = (PyObject *) (base0->ob_type); } Py_INCREF(meta); isclass = 1; /* meta is really a class */ } if (isclass) { /* meta is really a class, so check for a more derived metaclass, or possible metaclass conflicts: */ winner = (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)meta, bases); if (winner == NULL) { Py_DECREF(meta); Py_XDECREF(mkw); Py_DECREF(bases); return NULL; } if (winner != meta) { Py_DECREF(meta); meta = winner; Py_INCREF(meta); } } /* else: meta is not a class, so we cannot do the metaclass calculation, so we will use the explicitly given object as it is */ prep = _PyObject_GetAttrId(meta, &PyId___prepare__); if (prep == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); ns = PyDict_New(); } else { Py_DECREF(meta); Py_XDECREF(mkw); Py_DECREF(bases); return NULL; } } else { PyObject *pargs[2] = {name, bases}; ns = _PyObject_FastCallDict(prep, pargs, 2, mkw); Py_DECREF(prep); } if (ns == NULL) { Py_DECREF(meta); Py_XDECREF(mkw); Py_DECREF(bases); return NULL; } if (!PyMapping_Check(ns)) { PyErr_Format(PyExc_TypeError, "%.200s.__prepare__() must return a mapping, not %.200s", isclass ? ((PyTypeObject *)meta)->tp_name : "<metaclass>", Py_TYPE(ns)->tp_name); goto error; } cell = PyEval_EvalCodeEx(PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), ns, NULL, 0, NULL, 0, NULL, 0, NULL, PyFunction_GET_CLOSURE(func)); if (cell != NULL) { PyObject *margs[3] = {name, bases, ns}; cls = _PyObject_FastCallDict(meta, margs, 3, mkw); if (cls != NULL && PyType_Check(cls) && PyCell_Check(cell)) { PyObject *cell_cls = PyCell_GET(cell); if (cell_cls != cls) { /* TODO: In 3.7, DeprecationWarning will become RuntimeError. * At that point, cell_error won't be needed. */ int cell_error; if (cell_cls == NULL) { const char *msg = "__class__ not set defining %.200R as %.200R. " "Was __classcell__ propagated to type.__new__?"; cell_error = PyErr_WarnFormat( PyExc_DeprecationWarning, 1, msg, name, cls); } else { const char *msg = "__class__ set to %.200R defining %.200R as %.200R"; PyErr_Format(PyExc_TypeError, msg, cell_cls, name, cls); cell_error = 1; } if (cell_error) { Py_DECREF(cls); cls = NULL; goto error; } else { /* Fill in the cell, since type.__new__ didn't do it */ PyCell_Set(cell, cls); } } } } error: Py_XDECREF(cell); Py_DECREF(ns); Py_DECREF(meta); Py_XDECREF(mkw); Py_DECREF(bases); return cls; } PyDoc_STRVAR(build_class_doc, "__build_class__(func, name, *bases, metaclass=None, **kwds) -> class\n\ \n\ Internal helper function used by the class statement."); static PyObject * builtin___import__(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwds) { static const char * const kwlist[] = {"name", "globals", "locals", "fromlist", "level", 0}; PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL; int level = 0; static _PyArg_Parser _parser = {"U|OOOi:__import__", kwlist, 0}; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwds, &_parser, &name, &globals, &locals, &fromlist, &level)) return NULL; return PyImport_ImportModuleLevelObject(name, globals, locals, fromlist, level); } PyDoc_STRVAR(import_doc, "__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module\n\ \n\ Import a module. Because this function is meant for use by the Python\n\ interpreter and not for general use, it is better to use\n\ importlib.import_module() to programmatically import a module.\n\ \n\ The globals argument is only used to determine the context;\n\ they are not modified. The locals argument is unused. The fromlist\n\ should be a list of names to emulate ``from name import ...'', or an\n\ empty list to emulate ``import name''.\n\ When importing a module from a package, note that __import__('A.B', ...)\n\ returns package A when fromlist is empty, but its submodule B when\n\ fromlist is not empty. The level argument is used to determine whether to\n\ perform absolute or relative imports: 0 is absolute, while a positive number\n\ is the number of parent directories to search relative to the current module."); /*[clinic input] abs as builtin_abs x: object / Return the absolute value of the argument. [clinic start generated code]*/ static PyObject * builtin_abs(PyObject *module, PyObject *x) /*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/ { return PyNumber_Absolute(x); } /*[clinic input] all as builtin_all iterable: object / Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True. [clinic start generated code]*/ static PyObject * builtin_all(PyObject *module, PyObject *iterable) /*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/ { PyObject *it, *item; PyObject *(*iternext)(PyObject *); int cmp; it = PyObject_GetIter(iterable); if (it == NULL) return NULL; iternext = *Py_TYPE(it)->tp_iternext; for (;;) { item = iternext(it); if (item == NULL) break; cmp = PyObject_IsTrue(item); Py_DECREF(item); if (cmp < 0) { Py_DECREF(it); return NULL; } if (cmp == 0) { Py_DECREF(it); Py_RETURN_FALSE; } } Py_DECREF(it); if (PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_StopIteration)) PyErr_Clear(); else return NULL; } Py_RETURN_TRUE; } /*[clinic input] any as builtin_any iterable: object / Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False. [clinic start generated code]*/ static PyObject * builtin_any(PyObject *module, PyObject *iterable) /*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/ { PyObject *it, *item; PyObject *(*iternext)(PyObject *); int cmp; it = PyObject_GetIter(iterable); if (it == NULL) return NULL; iternext = *Py_TYPE(it)->tp_iternext; for (;;) { item = iternext(it); if (item == NULL) break; cmp = PyObject_IsTrue(item); Py_DECREF(item); if (cmp < 0) { Py_DECREF(it); return NULL; } if (cmp > 0) { Py_DECREF(it); Py_RETURN_TRUE; } } Py_DECREF(it); if (PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_StopIteration)) PyErr_Clear(); else return NULL; } Py_RETURN_FALSE; } /*[clinic input] ascii as builtin_ascii obj: object / Return an ASCII-only representation of an object. As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using \\x, \\u or \\U escapes. This generates a string similar to that returned by repr() in Python 2. [clinic start generated code]*/ static PyObject * builtin_ascii(PyObject *module, PyObject *obj) /*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/ { return PyObject_ASCII(obj); } /*[clinic input] bin as builtin_bin number: object / Return the binary representation of an integer. >>> bin(2796202) '0b1010101010101010101010' [clinic start generated code]*/ static PyObject * builtin_bin(PyObject *module, PyObject *number) /*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/ { return PyNumber_ToBase(number, 2); } /*[clinic input] callable as builtin_callable obj: object / Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances of classes with a __call__() method. [clinic start generated code]*/ static PyObject * builtin_callable(PyObject *module, PyObject *obj) /*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/ { return PyBool_FromLong((long)PyCallable_Check(obj)); } typedef struct { PyObject_HEAD PyObject *func; PyObject *it; } filterobject; static PyObject * filter_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *func, *seq; PyObject *it; filterobject *lz; if (type == &PyFilter_Type && !_PyArg_NoKeywords("filter()", kwds)) return NULL; if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq)) return NULL; /* Get iterator. */ it = PyObject_GetIter(seq); if (it == NULL) return NULL; /* create filterobject structure */ lz = (filterobject *)type->tp_alloc(type, 0); if (lz == NULL) { Py_DECREF(it); return NULL; } Py_INCREF(func); lz->func = func; lz->it = it; return (PyObject *)lz; } static void filter_dealloc(filterobject *lz) { PyObject_GC_UnTrack(lz); Py_XDECREF(lz->func); Py_XDECREF(lz->it); Py_TYPE(lz)->tp_free(lz); } static int filter_traverse(filterobject *lz, visitproc visit, void *arg) { Py_VISIT(lz->it); Py_VISIT(lz->func); return 0; } static PyObject * filter_next(filterobject *lz) { PyObject *item; PyObject *it = lz->it; long ok; PyObject *(*iternext)(PyObject *); int checktrue = lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type; iternext = *Py_TYPE(it)->tp_iternext; for (;;) { item = iternext(it); if (item == NULL) return NULL; if (checktrue) { ok = PyObject_IsTrue(item); } else { PyObject *good; good = PyObject_CallFunctionObjArgs(lz->func, item, NULL); if (good == NULL) { Py_DECREF(item); return NULL; } ok = PyObject_IsTrue(good); Py_DECREF(good); } if (ok > 0) return item; Py_DECREF(item); if (ok < 0) return NULL; } } static PyObject * filter_reduce(filterobject *lz) { return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->func, lz->it); } PyDoc_STRVAR(reduce_doc, "Return state information for pickling."); static PyMethodDef filter_methods[] = { {"__reduce__", (PyCFunction)filter_reduce, METH_NOARGS, reduce_doc}, {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(filter_doc, "filter(function or None, iterable) --> filter object\n\ \n\ Return an iterator yielding those items of iterable for which function(item)\n\ is true. If function is None, return the items that are true."); PyTypeObject PyFilter_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "filter", /* tp_name */ sizeof(filterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)filter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ filter_doc, /* tp_doc */ (traverseproc)filter_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)filter_next, /* tp_iternext */ filter_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ filter_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; /*[clinic input] format as builtin_format value: object format_spec: unicode(c_default="NULL") = '' / Return value.__format__(format_spec) format_spec defaults to the empty string. See the Format Specification Mini-Language section of help('FORMATTING') for details. [clinic start generated code]*/ static PyObject * builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec) /*[clinic end generated code: output=2f40bdfa4954b077 input=88339c93ea522b33]*/ { return PyObject_Format(value, format_spec); } /*[clinic input] chr as builtin_chr i: int / Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. [clinic start generated code]*/ static PyObject * builtin_chr_impl(PyObject *module, int i) /*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/ { return PyUnicode_FromOrdinal(i); } static const char * source_as_string(PyObject *cmd, const char *funcname, const char *what, PyCompilerFlags *cf, PyObject **cmd_copy) { const char *str; Py_ssize_t size; Py_buffer view; *cmd_copy = NULL; if (PyUnicode_Check(cmd)) { cf->cf_flags |= PyCF_IGNORE_COOKIE; str = PyUnicode_AsUTF8AndSize(cmd, &size); if (str == NULL) return NULL; } else if (PyBytes_Check(cmd)) { str = PyBytes_AS_STRING(cmd); size = PyBytes_GET_SIZE(cmd); } else if (PyByteArray_Check(cmd)) { str = PyByteArray_AS_STRING(cmd); size = PyByteArray_GET_SIZE(cmd); } else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) { /* Copy to NUL-terminated buffer. */ *cmd_copy = PyBytes_FromStringAndSize( (const char *)view.buf, view.len); PyBuffer_Release(&view); if (*cmd_copy == NULL) { return NULL; } str = PyBytes_AS_STRING(*cmd_copy); size = PyBytes_GET_SIZE(*cmd_copy); } else { PyErr_Format(PyExc_TypeError, "%s() arg 1 must be a %s object", funcname, what); return NULL; } if (strlen(str) != (size_t)size) { PyErr_SetString(PyExc_ValueError, "source code string cannot contain null bytes"); Py_CLEAR(*cmd_copy); return NULL; } return str; } /*[clinic input] compile as builtin_compile source: object filename: object(converter="PyUnicode_FSDecoder") mode: str flags: int = 0 dont_inherit: int(c_default="0") = False optimize: int = -1 Compile source into a code object that can be executed by exec() or eval(). The source code may represent a Python module, statement or expression. The filename will be used for run-time error messages. The mode must be 'exec' to compile a module, 'single' to compile a single (interactive) statement, or 'eval' to compile an expression. The flags argument, if present, controls which future statements influence the compilation of the code. The dont_inherit argument, if true, stops the compilation inheriting the effects of any future statements in effect in the code calling compile; if absent or false these statements do influence the compilation, in addition to any features explicitly specified. [clinic start generated code]*/ static PyObject * builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename, const char *mode, int flags, int dont_inherit, int optimize) /*[clinic end generated code: output=1fa176e33452bb63 input=9d53e8cfb3c86414]*/ { PyObject *source_copy; const char *str; int compile_mode = -1; int is_ast; PyCompilerFlags cf; int start[] = {Py_file_input, Py_eval_input, Py_single_input}; PyObject *result; cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8; if (flags & ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST)) { PyErr_SetString(PyExc_ValueError, "compile(): unrecognised flags"); goto error; } /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */ if (optimize < -1 || optimize > 2) { PyErr_SetString(PyExc_ValueError, "compile(): invalid optimize value"); goto error; } if (!dont_inherit) { PyEval_MergeCompilerFlags(&cf); } if (strcmp(mode, "exec") == 0) compile_mode = 0; else if (strcmp(mode, "eval") == 0) compile_mode = 1; else if (strcmp(mode, "single") == 0) compile_mode = 2; else { PyErr_SetString(PyExc_ValueError, "compile() mode must be 'exec', 'eval' or 'single'"); goto error; } is_ast = PyAST_Check(source); if (is_ast == -1) goto error; if (is_ast) { if (flags & PyCF_ONLY_AST) { Py_INCREF(source); result = source; } else { PyArena *arena; mod_ty mod; arena = PyArena_New(); if (arena == NULL) goto error; mod = PyAST_obj2mod(source, arena, compile_mode); if (mod == NULL) { PyArena_Free(arena); goto error; } if (!PyAST_Validate(mod)) { PyArena_Free(arena); goto error; } result = (PyObject*)PyAST_CompileObject(mod, filename, &cf, optimize, arena); PyArena_Free(arena); } goto finally; } str = source_as_string(source, "compile", "string, bytes or AST", &cf, &source_copy); if (str == NULL) goto error; result = Py_CompileStringObject(str, filename, start[compile_mode], &cf, optimize); Py_XDECREF(source_copy); goto finally; error: result = NULL; finally: Py_DECREF(filename); return result; } /* AC: cannot convert yet, as needs PEP 457 group support in inspect */ static PyObject * builtin_dir(PyObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *arg = NULL; if (!_PyArg_UnpackStack(args, nargs, "dir", 0, 1, &arg)) return NULL; return PyObject_Dir(arg); } PyDoc_STRVAR(dir_doc, "dir([object]) -> list of strings\n" "\n" "If called without an argument, return the names in the current scope.\n" "Else, return an alphabetized list of names comprising (some of) the attributes\n" "of the given object, and of attributes reachable from it.\n" "If the object supplies a method named __dir__, it will be used; otherwise\n" "the default dir() logic is used and returns:\n" " for a module object: the module's attributes.\n" " for a class object: its attributes, and recursively the attributes\n" " of its bases.\n" " for any other object: its attributes, its class's attributes, and\n" " recursively the attributes of its class's base classes."); /*[clinic input] divmod as builtin_divmod x: object y: object / Return the tuple (x//y, x%y). Invariant: div*y + mod == x. [clinic start generated code]*/ static PyObject * builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y) /*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/ { return PyNumber_Divmod(x, y); } /*[clinic input] eval as builtin_eval source: object globals: object = None locals: object = None / Evaluate the given source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it. [clinic start generated code]*/ static PyObject * builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals, PyObject *locals) /*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/ { PyObject *result, *source_copy; const char *str; PyCompilerFlags cf; if (locals != Py_None && !PyMapping_Check(locals)) { PyErr_SetString(PyExc_TypeError, "locals must be a mapping"); return NULL; } if (globals != Py_None && !PyDict_Check(globals)) { PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ? "globals must be a real dict; try eval(expr, {}, mapping)" : "globals must be a dict"); return NULL; } if (globals == Py_None) { globals = PyEval_GetGlobals(); if (locals == Py_None) { locals = PyEval_GetLocals(); if (locals == NULL) return NULL; } } else if (locals == Py_None) locals = globals; if (globals == NULL || locals == NULL) { PyErr_SetString(PyExc_TypeError, "eval must be given globals and locals " "when called without a frame"); return NULL; } if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) { if (_PyDict_SetItemId(globals, &PyId___builtins__, PyEval_GetBuiltins()) != 0) return NULL; } if (PyCode_Check(source)) { if (PyCode_GetNumFree((PyCodeObject *)source) > 0) { PyErr_SetString(PyExc_TypeError, "code object passed to eval() may not contain free variables"); return NULL; } return PyEval_EvalCode(source, globals, locals); } cf.cf_flags = PyCF_SOURCE_IS_UTF8; str = source_as_string(source, "eval", "string, bytes or code", &cf, &source_copy); if (str == NULL) return NULL; while (*str == ' ' || *str == '\t') str++; (void)PyEval_MergeCompilerFlags(&cf); result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf); Py_XDECREF(source_copy); return result; } /*[clinic input] exec as builtin_exec source: object globals: object = None locals: object = None / Execute the given source in the context of globals and locals. The source may be a string representing one or more Python statements or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it. [clinic start generated code]*/ static PyObject * builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals, PyObject *locals) /*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/ { PyObject *v; if (globals == Py_None) { globals = PyEval_GetGlobals(); if (locals == Py_None) { locals = PyEval_GetLocals(); if (locals == NULL) return NULL; } if (!globals || !locals) { PyErr_SetString(PyExc_SystemError, "globals and locals cannot be NULL"); return NULL; } } else if (locals == Py_None) locals = globals; if (!PyDict_Check(globals)) { PyErr_Format(PyExc_TypeError, "exec() globals must be a dict, not %.100s", globals->ob_type->tp_name); return NULL; } if (!PyMapping_Check(locals)) { PyErr_Format(PyExc_TypeError, "locals must be a mapping or None, not %.100s", locals->ob_type->tp_name); return NULL; } if (_PyDict_GetItemId(globals, &PyId___builtins__) == NULL) { if (_PyDict_SetItemId(globals, &PyId___builtins__, PyEval_GetBuiltins()) != 0) return NULL; } if (PyCode_Check(source)) { if (PyCode_GetNumFree((PyCodeObject *)source) > 0) { PyErr_SetString(PyExc_TypeError, "code object passed to exec() may not " "contain free variables"); return NULL; } v = PyEval_EvalCode(source, globals, locals); } else { PyObject *source_copy; const char *str; PyCompilerFlags cf; cf.cf_flags = PyCF_SOURCE_IS_UTF8; str = source_as_string(source, "exec", "string, bytes or code", &cf, &source_copy); if (str == NULL) return NULL; if (PyEval_MergeCompilerFlags(&cf)) v = PyRun_StringFlags(str, Py_file_input, globals, locals, &cf); else v = PyRun_String(str, Py_file_input, globals, locals); Py_XDECREF(source_copy); } if (v == NULL) return NULL; Py_DECREF(v); Py_RETURN_NONE; } PyObject * PyBuiltin_Exec(PyObject *module, PyObject *source, PyObject *globals, PyObject *locals) { return builtin_exec_impl(module, source, globals, locals); } /* AC: cannot convert yet, as needs PEP 457 group support in inspect */ static PyObject * builtin_getattr(PyObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *v, *result, *dflt = NULL; PyObject *name; if (!_PyArg_UnpackStack(args, nargs, "getattr", 2, 3, &v, &name, &dflt)) return NULL; if (!PyUnicode_Check(name)) { PyErr_SetString(PyExc_TypeError, "getattr(): attribute name must be string"); return NULL; } result = PyObject_GetAttr(v, name); if (result == NULL && dflt != NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); Py_INCREF(dflt); result = dflt; } return result; } PyDoc_STRVAR(getattr_doc, "getattr(object, name[, default]) -> value\n\ \n\ Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\ When a default argument is given, it is returned when the attribute doesn't\n\ exist; without it, an exception is raised in that case."); /*[clinic input] globals as builtin_globals Return the dictionary containing the current scope's global variables. NOTE: Updates to this dictionary *will* affect name lookups in the current global scope and vice-versa. [clinic start generated code]*/ static PyObject * builtin_globals_impl(PyObject *module) /*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/ { PyObject *d; d = PyEval_GetGlobals(); Py_XINCREF(d); return d; } /*[clinic input] hasattr as builtin_hasattr obj: object name: object / Return whether the object has an attribute with the given name. This is done by calling getattr(obj, name) and catching AttributeError. [clinic start generated code]*/ static PyObject * builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name) /*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/ { PyObject *v; if (!PyUnicode_Check(name)) { PyErr_SetString(PyExc_TypeError, "hasattr(): attribute name must be string"); return NULL; } v = PyObject_GetAttr(obj, name); if (v == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); Py_RETURN_FALSE; } return NULL; } Py_DECREF(v); Py_RETURN_TRUE; } /* AC: gdb's integration with CPython relies on builtin_id having * the *exact* parameter names of "self" and "v", so we ensure we * preserve those name rather than using the AC defaults. */ /*[clinic input] id as builtin_id self: self(type="PyModuleDef *") obj as v: object / Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.) [clinic start generated code]*/ static PyObject * builtin_id(PyModuleDef *self, PyObject *v) /*[clinic end generated code: output=0aa640785f697f65 input=5a534136419631f4]*/ { return PyLong_FromVoidPtr(v); } /* map object ************************************************************/ typedef struct { PyObject_HEAD PyObject *iters; PyObject *func; } mapobject; static PyObject * map_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *it, *iters, *func; mapobject *lz; Py_ssize_t numargs, i; if (type == &PyMap_Type && !_PyArg_NoKeywords("map()", kwds)) return NULL; numargs = PyTuple_Size(args); if (numargs < 2) { PyErr_SetString(PyExc_TypeError, "map() must have at least two arguments."); return NULL; } iters = PyTuple_New(numargs-1); if (iters == NULL) return NULL; for (i=1 ; i<numargs ; i++) { /* Get iterator. */ it = PyObject_GetIter(PyTuple_GET_ITEM(args, i)); if (it == NULL) { Py_DECREF(iters); return NULL; } PyTuple_SET_ITEM(iters, i-1, it); } /* create mapobject structure */ lz = (mapobject *)type->tp_alloc(type, 0); if (lz == NULL) { Py_DECREF(iters); return NULL; } lz->iters = iters; func = PyTuple_GET_ITEM(args, 0); Py_INCREF(func); lz->func = func; return (PyObject *)lz; } static void map_dealloc(mapobject *lz) { PyObject_GC_UnTrack(lz); Py_XDECREF(lz->iters); Py_XDECREF(lz->func); Py_TYPE(lz)->tp_free(lz); } static int map_traverse(mapobject *lz, visitproc visit, void *arg) { Py_VISIT(lz->iters); Py_VISIT(lz->func); return 0; } static PyObject * map_next(mapobject *lz) { PyObject *small_stack[5]; PyObject **stack; Py_ssize_t niters, nargs, i; PyObject *result = NULL; niters = PyTuple_GET_SIZE(lz->iters); if (niters <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) { stack = small_stack; } else { stack = PyMem_Malloc(niters * sizeof(stack[0])); if (stack == NULL) { PyErr_NoMemory(); return NULL; } } nargs = 0; for (i=0; i < niters; i++) { PyObject *it = PyTuple_GET_ITEM(lz->iters, i); PyObject *val = Py_TYPE(it)->tp_iternext(it); if (val == NULL) { goto exit; } stack[i] = val; nargs++; } result = _PyObject_FastCall(lz->func, stack, nargs); exit: for (i=0; i < nargs; i++) { Py_DECREF(stack[i]); } if (stack != small_stack) { PyMem_Free(stack); } return result; } static PyObject * map_reduce(mapobject *lz) { Py_ssize_t numargs = PyTuple_GET_SIZE(lz->iters); PyObject *args = PyTuple_New(numargs+1); Py_ssize_t i; if (args == NULL) return NULL; Py_INCREF(lz->func); PyTuple_SET_ITEM(args, 0, lz->func); for (i = 0; i<numargs; i++){ PyObject *it = PyTuple_GET_ITEM(lz->iters, i); Py_INCREF(it); PyTuple_SET_ITEM(args, i+1, it); } return Py_BuildValue("ON", Py_TYPE(lz), args); } static PyMethodDef map_methods[] = { {"__reduce__", (PyCFunction)map_reduce, METH_NOARGS, reduce_doc}, {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(map_doc, "map(func, *iterables) --> map object\n\ \n\ Make an iterator that computes the function using arguments from\n\ each of the iterables. Stops when the shortest iterable is exhausted."); PyTypeObject PyMap_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "map", /* tp_name */ sizeof(mapobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)map_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ map_doc, /* tp_doc */ (traverseproc)map_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)map_next, /* tp_iternext */ map_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ map_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; /* AC: cannot convert yet, as needs PEP 457 group support in inspect */ static PyObject * builtin_next(PyObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *it, *res; PyObject *def = NULL; if (!_PyArg_UnpackStack(args, nargs, "next", 1, 2, &it, &def)) return NULL; if (!PyIter_Check(it)) { PyErr_Format(PyExc_TypeError, "'%.200s' object is not an iterator", it->ob_type->tp_name); return NULL; } res = (*it->ob_type->tp_iternext)(it); if (res != NULL) { return res; } else if (def != NULL) { if (PyErr_Occurred()) { if(!PyErr_ExceptionMatches(PyExc_StopIteration)) return NULL; PyErr_Clear(); } Py_INCREF(def); return def; } else if (PyErr_Occurred()) { return NULL; } else { PyErr_SetNone(PyExc_StopIteration); return NULL; } } PyDoc_STRVAR(next_doc, "next(iterator[, default])\n\ \n\ Return the next item from the iterator. If default is given and the iterator\n\ is exhausted, it is returned instead of raising StopIteration."); /*[clinic input] setattr as builtin_setattr obj: object name: object value: object / Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v'' [clinic start generated code]*/ static PyObject * builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name, PyObject *value) /*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/ { if (PyObject_SetAttr(obj, name, value) != 0) return NULL; Py_INCREF(Py_None); return Py_None; } /*[clinic input] delattr as builtin_delattr obj: object name: object / Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y'' [clinic start generated code]*/ static PyObject * builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name) /*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/ { if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0) return NULL; Py_INCREF(Py_None); return Py_None; } /*[clinic input] hash as builtin_hash obj: object / Return the hash value for the given object. Two objects that compare equal must also have the same hash value, but the reverse is not necessarily true. [clinic start generated code]*/ static PyObject * builtin_hash(PyObject *module, PyObject *obj) /*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/ { Py_hash_t x; x = PyObject_Hash(obj); if (x == -1) return NULL; return PyLong_FromSsize_t(x); } /*[clinic input] hex as builtin_hex number: object / Return the hexadecimal representation of an integer. >>> hex(12648430) '0xc0ffee' [clinic start generated code]*/ static PyObject * builtin_hex(PyObject *module, PyObject *number) /*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/ { return PyNumber_ToBase(number, 16); } /* AC: cannot convert yet, as needs PEP 457 group support in inspect */ static PyObject * builtin_iter(PyObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *v, *w = NULL; if (!_PyArg_UnpackStack(args, nargs, "iter", 1, 2, &v, &w)) return NULL; if (w == NULL) return PyObject_GetIter(v); if (!PyCallable_Check(v)) { PyErr_SetString(PyExc_TypeError, "iter(v, w): v must be callable"); return NULL; } return PyCallIter_New(v, w); } PyDoc_STRVAR(iter_doc, "iter(iterable) -> iterator\n\ iter(callable, sentinel) -> iterator\n\ \n\ Get an iterator from an object. In the first form, the argument must\n\ supply its own iterator, or be a sequence.\n\ In the second form, the callable is called until it returns the sentinel."); /*[clinic input] len as builtin_len obj: object / Return the number of items in a container. [clinic start generated code]*/ static PyObject * builtin_len(PyObject *module, PyObject *obj) /*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/ { Py_ssize_t res; res = PyObject_Size(obj); if (res < 0 && PyErr_Occurred()) return NULL; return PyLong_FromSsize_t(res); } /*[clinic input] locals as builtin_locals Return a dictionary containing the current scope's local variables. NOTE: Whether or not updates to this dictionary will affect name lookups in the local scope and vice-versa is *implementation dependent* and not covered by any backwards compatibility guarantees. [clinic start generated code]*/ static PyObject * builtin_locals_impl(PyObject *module) /*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/ { PyObject *d; d = PyEval_GetLocals(); Py_XINCREF(d); return d; } static PyObject * min_max(PyObject *args, PyObject *kwds, int op) { PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL; PyObject *emptytuple, *defaultval = NULL; static char *kwlist[] = {"key", "default", NULL}; const char *name = op == Py_LT ? "min" : "max"; const int positional = PyTuple_Size(args) > 1; int ret; if (positional) v = args; else if (!PyArg_UnpackTuple(args, name, 1, 1, &v)) return NULL; emptytuple = PyTuple_New(0); if (emptytuple == NULL) return NULL; ret = PyArg_ParseTupleAndKeywords(emptytuple, kwds, "|$OO", kwlist, &keyfunc, &defaultval); Py_DECREF(emptytuple); if (!ret) return NULL; if (positional && defaultval != NULL) { PyErr_Format(PyExc_TypeError, "Cannot specify a default for %s() with multiple " "positional arguments", name); return NULL; } it = PyObject_GetIter(v); if (it == NULL) { return NULL; } maxitem = NULL; /* the result */ maxval = NULL; /* the value associated with the result */ while (( item = PyIter_Next(it) )) { /* get the value from the key function */ if (keyfunc != NULL) { val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL); if (val == NULL) goto Fail_it_item; } /* no key function; the value is the item */ else { val = item; Py_INCREF(val); } /* maximum value and item are unset; set them */ if (maxval == NULL) { maxitem = item; maxval = val; } /* maximum value and item are set; update them as necessary */ else { int cmp = PyObject_RichCompareBool(val, maxval, op); if (cmp < 0) goto Fail_it_item_and_val; else if (cmp > 0) { Py_DECREF(maxval); Py_DECREF(maxitem); maxval = val; maxitem = item; } else { Py_DECREF(item); Py_DECREF(val); } } } if (PyErr_Occurred()) goto Fail_it; if (maxval == NULL) { assert(maxitem == NULL); if (defaultval != NULL) { Py_INCREF(defaultval); maxitem = defaultval; } else { PyErr_Format(PyExc_ValueError, "%s() arg is an empty sequence", name); } } else Py_DECREF(maxval); Py_DECREF(it); return maxitem; Fail_it_item_and_val: Py_DECREF(val); Fail_it_item: Py_DECREF(item); Fail_it: Py_XDECREF(maxval); Py_XDECREF(maxitem); Py_DECREF(it); return NULL; } /* AC: cannot convert yet, waiting for *args support */ static PyObject * builtin_min(PyObject *self, PyObject *args, PyObject *kwds) { return min_max(args, kwds, Py_LT); } PyDoc_STRVAR(min_doc, "min(iterable, *[, default=obj, key=func]) -> value\n\ min(arg1, arg2, *args, *[, key=func]) -> value\n\ \n\ With a single iterable argument, return its smallest item. The\n\ default keyword-only argument specifies an object to return if\n\ the provided iterable is empty.\n\ With two or more arguments, return the smallest argument."); /* AC: cannot convert yet, waiting for *args support */ static PyObject * builtin_max(PyObject *self, PyObject *args, PyObject *kwds) { return min_max(args, kwds, Py_GT); } PyDoc_STRVAR(max_doc, "max(iterable, *[, default=obj, key=func]) -> value\n\ max(arg1, arg2, *args, *[, key=func]) -> value\n\ \n\ With a single iterable argument, return its biggest item. The\n\ default keyword-only argument specifies an object to return if\n\ the provided iterable is empty.\n\ With two or more arguments, return the largest argument."); /*[clinic input] oct as builtin_oct number: object / Return the octal representation of an integer. >>> oct(342391) '0o1234567' [clinic start generated code]*/ static PyObject * builtin_oct(PyObject *module, PyObject *number) /*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/ { return PyNumber_ToBase(number, 8); } /*[clinic input] ord as builtin_ord c: object / Return the Unicode code point for a one-character string. [clinic start generated code]*/ static PyObject * builtin_ord(PyObject *module, PyObject *c) /*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/ { long ord; Py_ssize_t size; if (PyBytes_Check(c)) { size = PyBytes_GET_SIZE(c); if (size == 1) { ord = (long)((unsigned char)*PyBytes_AS_STRING(c)); return PyLong_FromLong(ord); } } else if (PyUnicode_Check(c)) { if (PyUnicode_READY(c) == -1) return NULL; size = PyUnicode_GET_LENGTH(c); if (size == 1) { ord = (long)PyUnicode_READ_CHAR(c, 0); return PyLong_FromLong(ord); } } else if (PyByteArray_Check(c)) { /* XXX Hopefully this is temporary */ size = PyByteArray_GET_SIZE(c); if (size == 1) { ord = (long)((unsigned char)*PyByteArray_AS_STRING(c)); return PyLong_FromLong(ord); } } else { PyErr_Format(PyExc_TypeError, "ord() expected string of length 1, but " \ "%.200s found", c->ob_type->tp_name); return NULL; } PyErr_Format(PyExc_TypeError, "ord() expected a character, " "but string of length %zd found", size); return NULL; } /*[clinic input] pow as builtin_pow x: object y: object z: object = None / Equivalent to x**y (with two arguments) or x**y % z (with three arguments) Some types, such as ints, are able to use a more efficient algorithm when invoked using the three argument form. [clinic start generated code]*/ static PyObject * builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z) /*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/ { return PyNumber_Power(x, y, z); } /* AC: cannot convert yet, waiting for *args support */ static PyObject * builtin_print(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { static const char * const _keywords[] = {"sep", "end", "file", "flush", 0}; static struct _PyArg_Parser _parser = {"|OOOO:print", _keywords, 0}; PyObject *sep = NULL, *end = NULL, *file = NULL, *flush = NULL; int i, err; if (kwnames != NULL && !_PyArg_ParseStackAndKeywords(args + nargs, 0, kwnames, &_parser, &sep, &end, &file, &flush)) { return NULL; } if (file == NULL || file == Py_None) { file = _PySys_GetObjectId(&PyId_stdout); if (file == NULL) { PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout"); return NULL; } /* sys.stdout may be None when FILE* stdout isn't connected */ if (file == Py_None) Py_RETURN_NONE; } if (sep == Py_None) { sep = NULL; } else if (sep && !PyUnicode_Check(sep)) { PyErr_Format(PyExc_TypeError, "sep must be None or a string, not %.200s", sep->ob_type->tp_name); return NULL; } if (end == Py_None) { end = NULL; } else if (end && !PyUnicode_Check(end)) { PyErr_Format(PyExc_TypeError, "end must be None or a string, not %.200s", end->ob_type->tp_name); return NULL; } for (i = 0; i < nargs; i++) { if (i > 0) { if (sep == NULL) err = PyFile_WriteString(" ", file); else err = PyFile_WriteObject(sep, file, Py_PRINT_RAW); if (err) return NULL; } err = PyFile_WriteObject(args[i], file, Py_PRINT_RAW); if (err) return NULL; } if (end == NULL) err = PyFile_WriteString("\n", file); else err = PyFile_WriteObject(end, file, Py_PRINT_RAW); if (err) return NULL; if (flush != NULL) { PyObject *tmp; int do_flush = PyObject_IsTrue(flush); if (do_flush == -1) return NULL; else if (do_flush) { tmp = _PyObject_CallMethodId(file, &PyId_flush, NULL); if (tmp == NULL) return NULL; else Py_DECREF(tmp); } } Py_RETURN_NONE; } PyDoc_STRVAR(print_doc, "print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\ \n\ Prints the values to a stream, or to sys.stdout by default.\n\ Optional keyword arguments:\n\ file: a file-like object (stream); defaults to the current sys.stdout.\n\ sep: string inserted between values, default a space.\n\ end: string appended after the last value, default a newline.\n\ flush: whether to forcibly flush the stream."); /*[clinic input] input as builtin_input prompt: object(c_default="NULL") = None / Read a string from standard input. The trailing newline is stripped. The prompt string, if given, is printed to standard output without a trailing newline before reading input. If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. On *nix systems, readline is used if available. [clinic start generated code]*/ static PyObject * builtin_input_impl(PyObject *module, PyObject *prompt) /*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/ { PyObject *fin = _PySys_GetObjectId(&PyId_stdin); PyObject *fout = _PySys_GetObjectId(&PyId_stdout); PyObject *ferr = _PySys_GetObjectId(&PyId_stderr); PyObject *tmp; long fd; int tty; /* Check that stdin/out/err are intact */ if (fin == NULL || fin == Py_None) { PyErr_SetString(PyExc_RuntimeError, "input(): lost sys.stdin"); return NULL; } if (fout == NULL || fout == Py_None) { PyErr_SetString(PyExc_RuntimeError, "input(): lost sys.stdout"); return NULL; } if (ferr == NULL || ferr == Py_None) { PyErr_SetString(PyExc_RuntimeError, "input(): lost sys.stderr"); return NULL; } /* First of all, flush stderr */ tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL); if (tmp == NULL) PyErr_Clear(); else Py_DECREF(tmp); /* We should only use (GNU) readline if Python's sys.stdin and sys.stdout are the same as C's stdin and stdout, because we need to pass it those. */ tmp = _PyObject_CallMethodId(fin, &PyId_fileno, NULL); if (tmp == NULL) { PyErr_Clear(); tty = 0; } else { fd = PyLong_AsLong(tmp); Py_DECREF(tmp); if (fd < 0 && PyErr_Occurred()) return NULL; tty = fd == fileno(stdin) && isatty(fd); } if (tty) { tmp = _PyObject_CallMethodId(fout, &PyId_fileno, NULL); if (tmp == NULL) { PyErr_Clear(); tty = 0; } else { fd = PyLong_AsLong(tmp); Py_DECREF(tmp); if (fd < 0 && PyErr_Occurred()) return NULL; tty = fd == fileno(stdout) && isatty(fd); } } /* If we're interactive, use (GNU) readline */ if (tty) { PyObject *po = NULL; char *promptstr; char *s = NULL; PyObject *stdin_encoding = NULL, *stdin_errors = NULL; PyObject *stdout_encoding = NULL, *stdout_errors = NULL; char *stdin_encoding_str, *stdin_errors_str; PyObject *result; size_t len; /* stdin is a text stream, so it must have an encoding. */ stdin_encoding = _PyObject_GetAttrId(fin, &PyId_encoding); stdin_errors = _PyObject_GetAttrId(fin, &PyId_errors); if (!stdin_encoding || !stdin_errors || !PyUnicode_Check(stdin_encoding) || !PyUnicode_Check(stdin_errors)) { tty = 0; goto _readline_errors; } stdin_encoding_str = PyUnicode_AsUTF8(stdin_encoding); stdin_errors_str = PyUnicode_AsUTF8(stdin_errors); if (!stdin_encoding_str || !stdin_errors_str) goto _readline_errors; tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL); if (tmp == NULL) PyErr_Clear(); else Py_DECREF(tmp); if (prompt != NULL) { /* We have a prompt, encode it as stdout would */ char *stdout_encoding_str, *stdout_errors_str; PyObject *stringpo; stdout_encoding = _PyObject_GetAttrId(fout, &PyId_encoding); stdout_errors = _PyObject_GetAttrId(fout, &PyId_errors); if (!stdout_encoding || !stdout_errors || !PyUnicode_Check(stdout_encoding) || !PyUnicode_Check(stdout_errors)) { tty = 0; goto _readline_errors; } stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding); stdout_errors_str = PyUnicode_AsUTF8(stdout_errors); if (!stdout_encoding_str || !stdout_errors_str) goto _readline_errors; stringpo = PyObject_Str(prompt); if (stringpo == NULL) goto _readline_errors; po = PyUnicode_AsEncodedString(stringpo, stdout_encoding_str, stdout_errors_str); Py_CLEAR(stdout_encoding); Py_CLEAR(stdout_errors); Py_CLEAR(stringpo); if (po == NULL) goto _readline_errors; assert(PyBytes_Check(po)); promptstr = PyBytes_AS_STRING(po); } else { po = NULL; promptstr = ""; } s = PyOS_Readline(stdin, stdout, promptstr); if (s == NULL) { PyErr_CheckSignals(); if (!PyErr_Occurred()) PyErr_SetNone(PyExc_KeyboardInterrupt); goto _readline_errors; } len = strlen(s); if (len == 0) { PyErr_SetNone(PyExc_EOFError); result = NULL; } else { if (len > PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "input: input too long"); result = NULL; } else { len--; /* strip trailing '\n' */ if (len != 0 && s[len-1] == '\r') len--; /* strip trailing '\r' */ result = PyUnicode_Decode(s, len, stdin_encoding_str, stdin_errors_str); } } Py_DECREF(stdin_encoding); Py_DECREF(stdin_errors); Py_XDECREF(po); PyMem_FREE(s); return result; _readline_errors: Py_XDECREF(stdin_encoding); Py_XDECREF(stdout_encoding); Py_XDECREF(stdin_errors); Py_XDECREF(stdout_errors); Py_XDECREF(po); if (tty) return NULL; PyErr_Clear(); } /* Fallback if we're not interactive */ if (prompt != NULL) { if (PyFile_WriteObject(prompt, fout, Py_PRINT_RAW) != 0) return NULL; } tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL); if (tmp == NULL) PyErr_Clear(); else Py_DECREF(tmp); return PyFile_GetLine(fin, -1); } /*[clinic input] repr as builtin_repr obj: object / Return the canonical string representation of the object. For many object types, including most builtins, eval(repr(obj)) == obj. [clinic start generated code]*/ static PyObject * builtin_repr(PyObject *module, PyObject *obj) /*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/ { return PyObject_Repr(obj); } /* AC: cannot convert yet, as needs PEP 457 group support in inspect * or a semantic change to accept None for "ndigits" */ static PyObject * builtin_round(PyObject *self, PyObject *args, PyObject *kwds) { PyObject *ndigits = NULL; static char *kwlist[] = {"number", "ndigits", 0}; PyObject *number, *round, *result; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:round", kwlist, &number, &ndigits)) return NULL; if (Py_TYPE(number)->tp_dict == NULL) { if (PyType_Ready(Py_TYPE(number)) < 0) return NULL; } round = _PyObject_LookupSpecial(number, &PyId___round__); if (round == NULL) { if (!PyErr_Occurred()) PyErr_Format(PyExc_TypeError, "type %.100s doesn't define __round__ method", Py_TYPE(number)->tp_name); return NULL; } if (ndigits == NULL || ndigits == Py_None) result = PyObject_CallFunctionObjArgs(round, NULL); else result = PyObject_CallFunctionObjArgs(round, ndigits, NULL); Py_DECREF(round); return result; } PyDoc_STRVAR(round_doc, "round(number[, ndigits]) -> number\n\ \n\ Round a number to a given precision in decimal digits (default 0 digits).\n\ This returns an int when called with one argument, otherwise the\n\ same type as the number. ndigits may be negative."); /*AC: we need to keep the kwds dict intact to easily call into the * list.sort method, which isn't currently supported in AC. So we just use * the initially generated signature with a custom implementation. */ /* [disabled clinic input] sorted as builtin_sorted iterable as seq: object key as keyfunc: object = None reverse: object = False Return a new list containing all items from the iterable in ascending order. A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order. [end disabled clinic input]*/ PyDoc_STRVAR(builtin_sorted__doc__, "sorted($module, iterable, /, *, key=None, reverse=False)\n" "--\n" "\n" "Return a new list containing all items from the iterable in ascending order.\n" "\n" "A custom key function can be supplied to customize the sort order, and the\n" "reverse flag can be set to request the result in descending order."); #define BUILTIN_SORTED_METHODDEF \ {"sorted", (PyCFunction)builtin_sorted, METH_FASTCALL | METH_KEYWORDS, builtin_sorted__doc__}, static PyObject * builtin_sorted(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames) { PyObject *newlist, *v, *seq, *keyfunc=NULL; PyObject *callable; static const char * const kwlist[] = {"", "key", "reverse", 0}; /* args 1-3 should match listsort in Objects/listobject.c */ static _PyArg_Parser parser = {"O|Oi:sorted", kwlist, 0}; int reverse; if (!_PyArg_ParseStackAndKeywords(args, nargs, kwnames, &parser, &seq, &keyfunc, &reverse)) return NULL; newlist = PySequence_List(seq); if (newlist == NULL) return NULL; callable = _PyObject_GetAttrId(newlist, &PyId_sort); if (callable == NULL) { Py_DECREF(newlist); return NULL; } v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames); Py_DECREF(callable); if (v == NULL) { Py_DECREF(newlist); return NULL; } Py_DECREF(v); return newlist; } /* AC: cannot convert yet, as needs PEP 457 group support in inspect */ static PyObject * builtin_vars(PyObject *self, PyObject **args, Py_ssize_t nargs) { PyObject *v = NULL; PyObject *d; if (!_PyArg_UnpackStack(args, nargs, "vars", 0, 1, &v)) return NULL; if (v == NULL) { d = PyEval_GetLocals(); if (d == NULL) return NULL; Py_INCREF(d); } else { d = _PyObject_GetAttrId(v, &PyId___dict__); if (d == NULL) { PyErr_SetString(PyExc_TypeError, "vars() argument must have __dict__ attribute"); return NULL; } } return d; } PyDoc_STRVAR(vars_doc, "vars([object]) -> dictionary\n\ \n\ Without arguments, equivalent to locals().\n\ With an argument, equivalent to object.__dict__."); /*[clinic input] sum as builtin_sum iterable: object start: object(c_default="NULL") = 0 / Return the sum of a 'start' value (default: 0) plus an iterable of numbers When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types. [clinic start generated code]*/ static PyObject * builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start) /*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/ { PyObject *result = start; PyObject *temp, *item, *iter; iter = PyObject_GetIter(iterable); if (iter == NULL) return NULL; if (result == NULL) { result = PyLong_FromLong(0); if (result == NULL) { Py_DECREF(iter); return NULL; } } else { /* reject string values for 'start' parameter */ if (PyUnicode_Check(result)) { PyErr_SetString(PyExc_TypeError, "sum() can't sum strings [use ''.join(seq) instead]"); Py_DECREF(iter); return NULL; } if (PyBytes_Check(result)) { PyErr_SetString(PyExc_TypeError, "sum() can't sum bytes [use b''.join(seq) instead]"); Py_DECREF(iter); return NULL; } if (PyByteArray_Check(result)) { PyErr_SetString(PyExc_TypeError, "sum() can't sum bytearray [use b''.join(seq) instead]"); Py_DECREF(iter); return NULL; } Py_INCREF(result); } #ifndef SLOW_SUM /* Fast addition by keeping temporary sums in C instead of new Python objects. Assumes all inputs are the same type. If the assumption fails, default to the more general routine. */ if (PyLong_CheckExact(result)) { int overflow; long i_result = PyLong_AsLongAndOverflow(result, &overflow); /* If this already overflowed, don't even enter the loop. */ if (overflow == 0) { Py_DECREF(result); result = NULL; } while(result == NULL) { item = PyIter_Next(iter); if (item == NULL) { Py_DECREF(iter); if (PyErr_Occurred()) return NULL; return PyLong_FromLong(i_result); } if (PyLong_CheckExact(item)) { long b = PyLong_AsLongAndOverflow(item, &overflow); long x = i_result + b; if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) { i_result = x; Py_DECREF(item); continue; } } /* Either overflowed or is not an int. Restore real objects and process normally */ result = PyLong_FromLong(i_result); if (result == NULL) { Py_DECREF(item); Py_DECREF(iter); return NULL; } temp = PyNumber_Add(result, item); Py_DECREF(result); Py_DECREF(item); result = temp; if (result == NULL) { Py_DECREF(iter); return NULL; } } } if (PyFloat_CheckExact(result)) { double f_result = PyFloat_AS_DOUBLE(result); Py_DECREF(result); result = NULL; while(result == NULL) { item = PyIter_Next(iter); if (item == NULL) { Py_DECREF(iter); if (PyErr_Occurred()) return NULL; return PyFloat_FromDouble(f_result); } if (PyFloat_CheckExact(item)) { PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) f_result += PyFloat_AS_DOUBLE(item); PyFPE_END_PROTECT(f_result) Py_DECREF(item); continue; } if (PyLong_CheckExact(item)) { long value; int overflow; value = PyLong_AsLongAndOverflow(item, &overflow); if (!overflow) { PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0) f_result += (double)value; PyFPE_END_PROTECT(f_result) Py_DECREF(item); continue; } } result = PyFloat_FromDouble(f_result); if (result == NULL) { Py_DECREF(item); Py_DECREF(iter); return NULL; } temp = PyNumber_Add(result, item); Py_DECREF(result); Py_DECREF(item); result = temp; if (result == NULL) { Py_DECREF(iter); return NULL; } } } #endif for(;;) { item = PyIter_Next(iter); if (item == NULL) { /* error, or end-of-sequence */ if (PyErr_Occurred()) { Py_DECREF(result); result = NULL; } break; } /* It's tempting to use PyNumber_InPlaceAdd instead of PyNumber_Add here, to avoid quadratic running time when doing 'sum(list_of_lists, [])'. However, this would produce a change in behaviour: a snippet like empty = [] sum([[x] for x in range(10)], empty) would change the value of empty. */ temp = PyNumber_Add(result, item); Py_DECREF(result); Py_DECREF(item); result = temp; if (result == NULL) break; } Py_DECREF(iter); return result; } /*[clinic input] isinstance as builtin_isinstance obj: object class_or_tuple: object / Return whether an object is an instance of a class or of a subclass thereof. A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B) or ...`` etc. [clinic start generated code]*/ static PyObject * builtin_isinstance_impl(PyObject *module, PyObject *obj, PyObject *class_or_tuple) /*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/ { int retval; retval = PyObject_IsInstance(obj, class_or_tuple); if (retval < 0) return NULL; return PyBool_FromLong(retval); } /*[clinic input] issubclass as builtin_issubclass cls: object class_or_tuple: object / Return whether 'cls' is a derived from another class or is the same class. A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B) or ...`` etc. [clinic start generated code]*/ static PyObject * builtin_issubclass_impl(PyObject *module, PyObject *cls, PyObject *class_or_tuple) /*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/ { int retval; retval = PyObject_IsSubclass(cls, class_or_tuple); if (retval < 0) return NULL; return PyBool_FromLong(retval); } typedef struct { PyObject_HEAD Py_ssize_t tuplesize; PyObject *ittuple; /* tuple of iterators */ PyObject *result; } zipobject; static PyObject * zip_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { zipobject *lz; Py_ssize_t i; PyObject *ittuple; /* tuple of iterators */ PyObject *result; Py_ssize_t tuplesize = PySequence_Length(args); if (type == &PyZip_Type && !_PyArg_NoKeywords("zip()", kwds)) return NULL; /* args must be a tuple */ assert(PyTuple_Check(args)); /* obtain iterators */ ittuple = PyTuple_New(tuplesize); if (ittuple == NULL) return NULL; for (i=0; i < tuplesize; ++i) { PyObject *item = PyTuple_GET_ITEM(args, i); PyObject *it = PyObject_GetIter(item); if (it == NULL) { if (PyErr_ExceptionMatches(PyExc_TypeError)) PyErr_Format(PyExc_TypeError, "zip argument #%zd must support iteration", i+1); Py_DECREF(ittuple); return NULL; } PyTuple_SET_ITEM(ittuple, i, it); } /* create a result holder */ result = PyTuple_New(tuplesize); if (result == NULL) { Py_DECREF(ittuple); return NULL; } for (i=0 ; i < tuplesize ; i++) { Py_INCREF(Py_None); PyTuple_SET_ITEM(result, i, Py_None); } /* create zipobject structure */ lz = (zipobject *)type->tp_alloc(type, 0); if (lz == NULL) { Py_DECREF(ittuple); Py_DECREF(result); return NULL; } lz->ittuple = ittuple; lz->tuplesize = tuplesize; lz->result = result; return (PyObject *)lz; } static void zip_dealloc(zipobject *lz) { PyObject_GC_UnTrack(lz); Py_XDECREF(lz->ittuple); Py_XDECREF(lz->result); Py_TYPE(lz)->tp_free(lz); } static int zip_traverse(zipobject *lz, visitproc visit, void *arg) { Py_VISIT(lz->ittuple); Py_VISIT(lz->result); return 0; } static PyObject * zip_next(zipobject *lz) { Py_ssize_t i; Py_ssize_t tuplesize = lz->tuplesize; PyObject *result = lz->result; PyObject *it; PyObject *item; PyObject *olditem; if (tuplesize == 0) return NULL; if (Py_REFCNT(result) == 1) { Py_INCREF(result); for (i=0 ; i < tuplesize ; i++) { it = PyTuple_GET_ITEM(lz->ittuple, i); item = (*Py_TYPE(it)->tp_iternext)(it); if (item == NULL) { Py_DECREF(result); return NULL; } olditem = PyTuple_GET_ITEM(result, i); PyTuple_SET_ITEM(result, i, item); Py_DECREF(olditem); } } else { result = PyTuple_New(tuplesize); if (result == NULL) return NULL; for (i=0 ; i < tuplesize ; i++) { it = PyTuple_GET_ITEM(lz->ittuple, i); item = (*Py_TYPE(it)->tp_iternext)(it); if (item == NULL) { Py_DECREF(result); return NULL; } PyTuple_SET_ITEM(result, i, item); } } return result; } static PyObject * zip_reduce(zipobject *lz) { /* Just recreate the zip with the internal iterator tuple */ return Py_BuildValue("OO", Py_TYPE(lz), lz->ittuple); } static PyMethodDef zip_methods[] = { {"__reduce__", (PyCFunction)zip_reduce, METH_NOARGS, reduce_doc}, {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(zip_doc, "zip(iter1 [,iter2 [...]]) --> zip object\n\ \n\ Return a zip object whose .__next__() method returns a tuple where\n\ the i-th element comes from the i-th iterable argument. The .__next__()\n\ method continues until the shortest iterable in the argument sequence\n\ is exhausted and then it raises StopIteration."); PyTypeObject PyZip_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "zip", /* tp_name */ sizeof(zipobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)zip_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ zip_doc, /* tp_doc */ (traverseproc)zip_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ PyObject_SelfIter, /* tp_iter */ (iternextfunc)zip_next, /* tp_iternext */ zip_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ zip_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; static PyMethodDef builtin_methods[] = { {"__build_class__", (PyCFunction)builtin___build_class__, METH_FASTCALL | METH_KEYWORDS, build_class_doc}, {"__import__", (PyCFunction)builtin___import__, METH_FASTCALL | METH_KEYWORDS, import_doc}, BUILTIN_ABS_METHODDEF BUILTIN_ALL_METHODDEF BUILTIN_ANY_METHODDEF BUILTIN_ASCII_METHODDEF BUILTIN_BIN_METHODDEF BUILTIN_CALLABLE_METHODDEF BUILTIN_CHR_METHODDEF BUILTIN_COMPILE_METHODDEF BUILTIN_DELATTR_METHODDEF {"dir", (PyCFunction)builtin_dir, METH_FASTCALL, dir_doc}, BUILTIN_DIVMOD_METHODDEF BUILTIN_EVAL_METHODDEF BUILTIN_EXEC_METHODDEF BUILTIN_FORMAT_METHODDEF {"getattr", (PyCFunction)builtin_getattr, METH_FASTCALL, getattr_doc}, BUILTIN_GLOBALS_METHODDEF BUILTIN_HASATTR_METHODDEF BUILTIN_HASH_METHODDEF BUILTIN_HEX_METHODDEF BUILTIN_ID_METHODDEF BUILTIN_INPUT_METHODDEF BUILTIN_ISINSTANCE_METHODDEF BUILTIN_ISSUBCLASS_METHODDEF {"iter", (PyCFunction)builtin_iter, METH_FASTCALL, iter_doc}, BUILTIN_LEN_METHODDEF BUILTIN_LOCALS_METHODDEF {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc}, {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc}, {"next", (PyCFunction)builtin_next, METH_FASTCALL, next_doc}, BUILTIN_OCT_METHODDEF BUILTIN_ORD_METHODDEF BUILTIN_POW_METHODDEF {"print", (PyCFunction)builtin_print, METH_FASTCALL | METH_KEYWORDS, print_doc}, BUILTIN_REPR_METHODDEF {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc}, BUILTIN_SETATTR_METHODDEF BUILTIN_SORTED_METHODDEF BUILTIN_SUM_METHODDEF {"vars", (PyCFunction)builtin_vars, METH_FASTCALL, vars_doc}, {NULL, NULL}, }; PyDoc_STRVAR(builtin_doc, "Built-in functions, exceptions, and other objects.\n\ \n\ Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices."); static struct PyModuleDef builtinsmodule = { PyModuleDef_HEAD_INIT, "builtins", builtin_doc, -1, /* multiple "initialization" just copies the module dict. */ builtin_methods, NULL, NULL, NULL, NULL }; PyObject * _PyBuiltin_Init(void) { PyObject *mod, *dict, *debug; if (PyType_Ready(&PyFilter_Type) < 0 || PyType_Ready(&PyMap_Type) < 0 || PyType_Ready(&PyZip_Type) < 0) return NULL; mod = PyModule_Create(&builtinsmodule); if (mod == NULL) return NULL; dict = PyModule_GetDict(mod); #ifdef Py_TRACE_REFS /* "builtins" exposes a number of statically allocated objects * that, before this code was added in 2.3, never showed up in * the list of "all objects" maintained by Py_TRACE_REFS. As a * result, programs leaking references to None and False (etc) * couldn't be diagnosed by examining sys.getobjects(0). */ #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0) #else #define ADD_TO_ALL(OBJECT) (void)0 #endif #define SETBUILTIN(NAME, OBJECT) \ if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \ return NULL; \ ADD_TO_ALL(OBJECT) SETBUILTIN("None", Py_None); SETBUILTIN("Ellipsis", Py_Ellipsis); SETBUILTIN("NotImplemented", Py_NotImplemented); SETBUILTIN("False", Py_False); SETBUILTIN("True", Py_True); SETBUILTIN("bool", &PyBool_Type); SETBUILTIN("memoryview", &PyMemoryView_Type); SETBUILTIN("bytearray", &PyByteArray_Type); SETBUILTIN("bytes", &PyBytes_Type); SETBUILTIN("classmethod", &PyClassMethod_Type); SETBUILTIN("complex", &PyComplex_Type); SETBUILTIN("dict", &PyDict_Type); SETBUILTIN("enumerate", &PyEnum_Type); SETBUILTIN("filter", &PyFilter_Type); SETBUILTIN("float", &PyFloat_Type); SETBUILTIN("frozenset", &PyFrozenSet_Type); SETBUILTIN("property", &PyProperty_Type); SETBUILTIN("int", &PyLong_Type); SETBUILTIN("list", &PyList_Type); SETBUILTIN("map", &PyMap_Type); SETBUILTIN("object", &PyBaseObject_Type); SETBUILTIN("range", &PyRange_Type); SETBUILTIN("reversed", &PyReversed_Type); SETBUILTIN("set", &PySet_Type); SETBUILTIN("slice", &PySlice_Type); SETBUILTIN("staticmethod", &PyStaticMethod_Type); SETBUILTIN("str", &PyUnicode_Type); SETBUILTIN("super", &PySuper_Type); SETBUILTIN("tuple", &PyTuple_Type); SETBUILTIN("type", &PyType_Type); SETBUILTIN("zip", &PyZip_Type); debug = PyBool_FromLong(Py_OptimizeFlag == 0); if (PyDict_SetItemString(dict, "__debug__", debug) < 0) { Py_DECREF(debug); return NULL; } Py_DECREF(debug); return mod; #undef ADD_TO_ALL #undef SETBUILTIN }
91,744
2,960
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/frozenmain.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "libc/stdio/stdio.h" #include "libc/str/locale.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/sysmodule.h" /* clang-format off */ #ifdef MS_WINDOWS extern void PyWinFreeze_ExeInit(void); extern void PyWinFreeze_ExeTerm(void); extern int PyInitFrozenExtensions(void); #endif int Py_FrozenMain(int argc, char **argv) { char *p; int i, n, sts = 1; int inspect = 0; int unbuffered = 0; char *oldloc = NULL; wchar_t **argv_copy = NULL; /* We need a second copies, as Python might modify the first one. */ wchar_t **argv_copy2 = NULL; if (argc > 0) { argv_copy = PyMem_RawMalloc(sizeof(wchar_t*) * argc); argv_copy2 = PyMem_RawMalloc(sizeof(wchar_t*) * argc); if (!argv_copy || !argv_copy2) { fprintf(stderr, "out of memory\n"); goto error; } } Py_FrozenFlag = 1; /* Suppress errors from getpath.c */ if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0') inspect = 1; if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0') unbuffered = 1; if (unbuffered) { setbuf(stdin, (char *)NULL); setbuf(stdout, (char *)NULL); setbuf(stderr, (char *)NULL); } oldloc = _PyMem_RawStrdup(setlocale(LC_ALL, NULL)); if (!oldloc) { fprintf(stderr, "out of memory\n"); goto error; } setlocale(LC_ALL, ""); for (i = 0; i < argc; i++) { argv_copy[i] = Py_DecodeLocale(argv[i], NULL); argv_copy2[i] = argv_copy[i]; if (!argv_copy[i]) { fprintf(stderr, "Unable to decode the command line argument #%i\n", i + 1); argc = i; goto error; } } setlocale(LC_ALL, oldloc); PyMem_RawFree(oldloc); oldloc = NULL; #ifdef MS_WINDOWS PyInitFrozenExtensions(); #endif /* MS_WINDOWS */ if (argc >= 1) Py_SetProgramName(argv_copy[0]); Py_Initialize(); #ifdef MS_WINDOWS PyWinFreeze_ExeInit(); #endif if (Py_VerboseFlag) fprintf(stderr, "Python %s\n%s\n", Py_GetVersion(), Py_GetCopyright()); PySys_SetArgv(argc, argv_copy); n = PyImport_ImportFrozenModule("__main__"); if (n == 0) Py_FatalError("__main__ not frozen"); if (n < 0) { PyErr_Print(); sts = 1; } else sts = 0; if (inspect && isatty((int)fileno(stdin))) sts = PyRun_AnyFile(stdin, "<stdin>") != 0; #ifdef MS_WINDOWS PyWinFreeze_ExeTerm(); #endif if (Py_FinalizeEx() < 0) { sts = 120; } error: PyMem_RawFree(argv_copy); if (argv_copy2) { for (i = 0; i < argc; i++) PyMem_RawFree(argv_copy2[i]); PyMem_RawFree(argv_copy2); } PyMem_RawFree(oldloc); return sts; }
3,969
127
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pyfpe.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* clang-format off */ #include "third_party/python/pyconfig.h" #include "third_party/python/Include/pyfpe.h" /* * The signal handler for SIGFPE is actually declared in an external * module fpectl, or as preferred by the user. These variable * definitions are required in order to compile Python without * getting missing externals, but to actually handle SIGFPE requires * defining a handler and enabling generation of SIGFPE. */ #ifdef WANT_SIGFPE_HANDLER jmp_buf PyFPE_jbuf; int PyFPE_counter = 0; #endif /* Have this outside the above #ifdef, since some picky ANSI compilers issue a warning when compiling an empty file. */ double PyFPE_dummy(void *dummy) { return 1.0; }
1,506
31
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/dynamic_annotations.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/dynamic_annotations.h" /* 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 */ /* Each function is empty and called (via a macro) only in debug mode. The arguments are captured by dynamic tools at runtime. */ #if DYNAMIC_ANNOTATIONS_ENABLED == 1 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 *mem, long size){} void AnnotateExpectRace(const char *file, int line, const volatile void *mem, const char *description){} void AnnotateBenignRace(const char *file, int line, const volatile void *mem, const char *description){} void AnnotateBenignRaceSized(const char *file, int line, const volatile void *mem, 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 AnnotateIgnoreSyncBegin(const char *file, int line){} void AnnotateIgnoreSyncEnd(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){} static int GetRunningOnValgrind(void) { #ifdef RUNNING_ON_VALGRIND if (RUNNING_ON_VALGRIND) return 1; #endif #ifndef _MSC_VER char *running_on_valgrind_str = getenv("RUNNING_ON_VALGRIND"); if (running_on_valgrind_str) { return strcmp(running_on_valgrind_str, "0") != 0; } #else /* Visual Studio issues warnings if we use getenv, * so we use GetEnvironmentVariableA instead. */ char value[100] = "1"; int res = GetEnvironmentVariableA("RUNNING_ON_VALGRIND", value, sizeof(value)); /* value will remain "1" if res == 0 or res >= sizeof(value). The latter * can happen only if the given value is long, in this case it can't be "0". */ if (res > 0 && !strcmp(value, "0")) return 1; #endif return 0; } /* See the comments in dynamic_annotations.h */ int RunningOnValgrind(void) { static volatile int running_on_valgrind = -1; /* C doesn't have thread-safe initialization of statics, and we don't want to depend on pthread_once here, so hack it. */ int local_running_on_valgrind = running_on_valgrind; if (local_running_on_valgrind == -1) running_on_valgrind = local_running_on_valgrind = GetRunningOnValgrind(); return local_running_on_valgrind; } #endif /* DYNAMIC_ANNOTATIONS_ENABLED == 1 */
7,428
151
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/fatality.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/weaken.h" #include "libc/log/log.h" #include "libc/runtime/runtime.h" #include "libc/stdio/stdio.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/traceback.h" /* clang-format off */ _Py_IDENTIFIER(flush); _Py_IDENTIFIER(stdout); _Py_IDENTIFIER(stderr); /* Import the site module (not into __main__ though) */ static void _Py_FatalError_DumpTracebacks(int fd) { fputc('\n', stderr); fflush(stderr); /* display the current Python stack */ _Py_DumpTracebackThreads(fd, NULL, NULL); } /* Print the current exception (if an exception is set) with its traceback, or display the current Python stack. Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is called on catastrophic cases. Return 1 if the traceback was displayed, 0 otherwise. */ static int _Py_FatalError_PrintExc(int fd) { PyObject *ferr, *res; PyObject *exception, *v, *tb; int has_tb; PyErr_Fetch(&exception, &v, &tb); if (exception == NULL) { /* No current exception */ return 0; } ferr = _PySys_GetObjectId(&PyId_stderr); if (ferr == NULL || ferr == Py_None) { /* sys.stderr is not set yet or set to None, no need to try to display the exception */ return 0; } PyErr_NormalizeException(&exception, &v, &tb); if (tb == NULL) { tb = Py_None; Py_INCREF(tb); } PyException_SetTraceback(v, tb); if (exception == NULL) { /* PyErr_NormalizeException() failed */ return 0; } has_tb = (tb != Py_None); PyErr_Display(exception, v, tb); Py_XDECREF(exception); Py_XDECREF(v); Py_XDECREF(tb); /* sys.stderr may be buffered: call sys.stderr.flush() */ res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL); if (res == NULL) PyErr_Clear(); else Py_DECREF(res); return has_tb; } /* Print fatal error message and abort */ void Py_FatalError(const char *msg) { const int fd = fileno(stderr); static int reentrant = 0; #ifdef MS_WINDOWS size_t len; WCHAR* buffer; size_t i; #endif if (reentrant) { /* Py_FatalError() caused a second fatal error. Example: _Py_FlushStdFiles() raises a recursion error. */ goto exit; } reentrant = 1; fprintf(stderr, "Fatal Python error: %s\n", msg); fflush(stderr); /* it helps in Windows debug build */ /* Check if the current thread has a Python thread state and holds the GIL */ PyThreadState *tss_tstate = NULL; // PyGILState_GetThisThreadState(); if (tss_tstate != NULL) { PyThreadState *tstate = PyThreadState_GET(); if (tss_tstate != tstate) { /* The Python thread does not hold the GIL */ tss_tstate = NULL; } } else { /* Py_FatalError() has been called from a C thread which has no Python thread state. */ } int has_tstate_and_gil = (tss_tstate != NULL); /* If an exception is set, print the exception with its traceback */ if (!_Py_FatalError_PrintExc(fd)) { /* No exception is set, or an exception is set without traceback */ _Py_FatalError_DumpTracebacks(fd); } /* The main purpose of faulthandler is to display the traceback. We already * did our best to display it. So faulthandler can now be disabled. * (Don't trigger it on abort().) */ _PyFaulthandler_Fini(); /* Check if the current Python thread hold the GIL */ if (has_tstate_and_gil) { /* Flush sys.stdout and sys.stderr */ _Py_FlushStdFiles(); } #ifdef MS_WINDOWS len = strlen(msg); /* Convert the message to wchar_t. This uses a simple one-to-one conversion, assuming that the this error message actually uses ASCII only. If this ceases to be true, we will have to convert. */ buffer = alloca( (len+1) * (sizeof *buffer)); for( i=0; i<=len; ++i) buffer[i] = msg[i]; OutputDebugStringW(L"Fatal Python error: "); OutputDebugStringW(buffer); OutputDebugStringW(L"\n"); #endif /* MS_WINDOWS */ exit: #if defined(MS_WINDOWS) && defined(_DEBUG) DebugBreak(); #endif if (_weaken(__die)) _weaken(__die)(); abort(); }
5,298
166
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pystate.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/errno.h" #include "libc/intrin/pushpop.h" #include "libc/runtime/dlfcn.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/pyatomic.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" /* clang-format off */ #if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_UNDEFINED__) STATIC_YOINK("__die"); /* to guarantee backtraces */ #endif /* Thread and interpreter state structures and their interfaces */ #define ZERO(x) x = (typeof(x))pushpop(0L) #define GET_TSTATE() \ ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current)) #define SET_TSTATE(value) \ _Py_atomic_store_relaxed(&_PyThreadState_Current, (uintptr_t)(value)) #define GET_INTERP_STATE() \ (GET_TSTATE()->interp) /* -------------------------------------------------------------------------- CAUTION Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A number of these functions are advertised as safe to call when the GIL isn't held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL to avoid the expense of doing their own locking). -------------------------------------------------------------------------- */ int _PyGILState_check_enabled = 1; #ifdef WITH_THREAD #include "third_party/python/Include/pythread.h" static PyThread_type_lock head_mutex = NULL; /* Protects interp->tstate_head */ #define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock())) #define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK) #define HEAD_UNLOCK() PyThread_release_lock(head_mutex) /* The single PyInterpreterState used by this process' GILState implementation */ static PyInterpreterState *autoInterpreterState = NULL; static int autoTLSkey = -1; #else #define HEAD_INIT() /* Nothing */ #define HEAD_LOCK() /* Nothing */ #define HEAD_UNLOCK() /* Nothing */ #endif static PyInterpreterState *interp_head = NULL; static __PyCodeExtraState *coextra_head = NULL; /* Assuming the current thread holds the GIL, this is the PyThreadState for the current thread. */ _Py_atomic_address _PyThreadState_Current = {0}; PyThreadFrameGetter _PyThreadState_GetFrame = NULL; #ifdef WITH_THREAD static void _PyGILState_NoteThreadState(PyThreadState* tstate); #endif PyInterpreterState * PyInterpreterState_New(void) { PyInterpreterState *interp = (PyInterpreterState *) PyMem_RawMalloc(sizeof(PyInterpreterState)); if (interp != 0) { __PyCodeExtraState* coextra = PyMem_RawMalloc(sizeof(__PyCodeExtraState)); if (coextra == 0) { PyMem_RawFree(interp); return 0; } HEAD_INIT(); #ifdef WITH_THREAD if (head_mutex == 0) Py_FatalError("Can't initialize threads for interpreter"); #endif ZERO(interp->modules); ZERO(interp->modules_by_index); ZERO(interp->sysdict); ZERO(interp->builtins); ZERO(interp->builtins_copy); ZERO(interp->tstate_head); ZERO(interp->codec_search_path); ZERO(interp->codec_search_cache); ZERO(interp->codec_error_registry); ZERO(interp->codecs_initialized); ZERO(interp->fscodec_initialized); ZERO(interp->importlib); ZERO(interp->import_func); interp->eval_frame = _PyEval_EvalFrameDefault; ZERO(coextra->co_extra_user_count); coextra->interp = interp; #ifdef HAVE_DLOPEN #if HAVE_DECL_RTLD_NOW interp->dlopenflags = RTLD_NOW; #else interp->dlopenflags = RTLD_LAZY; #endif #endif HEAD_LOCK(); interp->next = interp_head; interp_head = interp; coextra->next = coextra_head; coextra_head = coextra; HEAD_UNLOCK(); } return interp; } void PyInterpreterState_Clear(PyInterpreterState *interp) { PyThreadState *p; HEAD_LOCK(); for (p = interp->tstate_head; p != NULL; p = p->next) PyThreadState_Clear(p); HEAD_UNLOCK(); Py_CLEAR(interp->codec_search_path); Py_CLEAR(interp->codec_search_cache); Py_CLEAR(interp->codec_error_registry); Py_CLEAR(interp->modules); Py_CLEAR(interp->modules_by_index); Py_CLEAR(interp->sysdict); Py_CLEAR(interp->builtins); Py_CLEAR(interp->builtins_copy); Py_CLEAR(interp->importlib); Py_CLEAR(interp->import_func); } static void zapthreads(PyInterpreterState *interp) { PyThreadState *p; /* No need to lock the mutex here because this should only happen when the threads are all really dead (XXX famous last words). */ while ((p = interp->tstate_head) != NULL) { PyThreadState_Delete(p); } } void PyInterpreterState_Delete(PyInterpreterState *interp) { PyInterpreterState **p; __PyCodeExtraState **pextra; zapthreads(interp); HEAD_LOCK(); for (p = &interp_head; /* N/A */; p = &(*p)->next) { if (*p == NULL) Py_FatalError( "PyInterpreterState_Delete: invalid interp"); if (*p == interp) break; } if (interp->tstate_head != NULL) Py_FatalError("PyInterpreterState_Delete: remaining threads"); *p = interp->next; for (pextra = &coextra_head; ; pextra = &(*pextra)->next) { if (*pextra == NULL) Py_FatalError( "PyInterpreterState_Delete: invalid extra"); __PyCodeExtraState* extra = *pextra; if (extra->interp == interp) { *pextra = extra->next; PyMem_RawFree(extra); break; } } HEAD_UNLOCK(); PyMem_RawFree(interp); #ifdef WITH_THREAD if (interp_head == NULL && head_mutex != NULL) { PyThread_free_lock(head_mutex); head_mutex = NULL; } #endif } /* Default implementation for _PyThreadState_GetFrame */ static struct _frame * threadstate_getframe(PyThreadState *self) { return self->frame; } static PyThreadState * new_threadstate(PyInterpreterState *interp, int init) { PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState)); if (_PyThreadState_GetFrame == 0) _PyThreadState_GetFrame = threadstate_getframe; if (tstate != 0) { tstate->interp = interp; ZERO(tstate->frame); ZERO(tstate->recursion_depth); ZERO(tstate->overflowed); ZERO(tstate->recursion_critical); ZERO(tstate->tracing); ZERO(tstate->use_tracing); ZERO(tstate->gilstate_counter); ZERO(tstate->async_exc); #ifdef WITH_THREAD tstate->thread_id = PyThread_get_thread_ident(); #else ZERO(tstate->thread_id); #endif ZERO(tstate->dict); ZERO(tstate->curexc_type); ZERO(tstate->curexc_value); ZERO(tstate->curexc_traceback); ZERO(tstate->exc_type); ZERO(tstate->exc_value); ZERO(tstate->exc_traceback); ZERO(tstate->c_profilefunc); ZERO(tstate->c_tracefunc); ZERO(tstate->c_profileobj); ZERO(tstate->c_traceobj); ZERO(tstate->trash_delete_nesting); ZERO(tstate->trash_delete_later); ZERO(tstate->on_delete); ZERO(tstate->on_delete_data); ZERO(tstate->coroutine_wrapper); ZERO(tstate->in_coroutine_wrapper); ZERO(tstate->async_gen_firstiter); ZERO(tstate->async_gen_finalizer); if (init) _PyThreadState_Init(tstate); HEAD_LOCK(); ZERO(tstate->prev); tstate->next = interp->tstate_head; if (tstate->next) tstate->next->prev = tstate; interp->tstate_head = tstate; HEAD_UNLOCK(); } return tstate; } PyThreadState * PyThreadState_New(PyInterpreterState *interp) { return new_threadstate(interp, 1); } PyThreadState * _PyThreadState_Prealloc(PyInterpreterState *interp) { return new_threadstate(interp, 0); } void _PyThreadState_Init(PyThreadState *tstate) { #ifdef WITH_THREAD _PyGILState_NoteThreadState(tstate); #endif } PyObject* PyState_FindModule(struct PyModuleDef* module) { Py_ssize_t index = module->m_base.m_index; PyInterpreterState *state = GET_INTERP_STATE(); PyObject *res; if (module->m_slots) { return NULL; } if (index == 0) return NULL; if (state->modules_by_index == NULL) return NULL; if (index >= PyList_GET_SIZE(state->modules_by_index)) return NULL; res = PyList_GET_ITEM(state->modules_by_index, index); return res==Py_None ? NULL : res; } int _PyState_AddModule(PyObject* module, struct PyModuleDef* def) { PyInterpreterState *state; if (!def) { assert(PyErr_Occurred()); return -1; } if (def->m_slots) { PyErr_SetString(PyExc_SystemError, "PyState_AddModule called on module with slots"); return -1; } state = GET_INTERP_STATE(); if (!state->modules_by_index) { state->modules_by_index = PyList_New(0); if (!state->modules_by_index) return -1; } while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index) if (PyList_Append(state->modules_by_index, Py_None) < 0) return -1; Py_INCREF(module); return PyList_SetItem(state->modules_by_index, def->m_base.m_index, module); } int PyState_AddModule(PyObject* module, struct PyModuleDef* def) { Py_ssize_t index; PyInterpreterState *state = GET_INTERP_STATE(); if (!def) { Py_FatalError("PyState_AddModule: Module Definition is NULL"); return -1; } index = def->m_base.m_index; if (state->modules_by_index) { if(PyList_GET_SIZE(state->modules_by_index) >= index) { if(module == PyList_GET_ITEM(state->modules_by_index, index)) { Py_FatalError("PyState_AddModule: Module already added!"); return -1; } } } return _PyState_AddModule(module, def); } int PyState_RemoveModule(struct PyModuleDef* def) { PyInterpreterState *state; Py_ssize_t index = def->m_base.m_index; if (def->m_slots) { PyErr_SetString(PyExc_SystemError, "PyState_RemoveModule called on module with slots"); return -1; } state = GET_INTERP_STATE(); if (index == 0) { Py_FatalError("PyState_RemoveModule: Module index invalid."); return -1; } if (state->modules_by_index == NULL) { Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible."); return -1; } if (index > PyList_GET_SIZE(state->modules_by_index)) { Py_FatalError("PyState_RemoveModule: Module index out of bounds."); return -1; } Py_INCREF(Py_None); return PyList_SetItem(state->modules_by_index, index, Py_None); } /* used by import.c:PyImport_Cleanup */ void _PyState_ClearModules(void) { PyInterpreterState *state = GET_INTERP_STATE(); if (state->modules_by_index) { Py_ssize_t i; for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) { PyObject *m = PyList_GET_ITEM(state->modules_by_index, i); if (PyModule_Check(m)) { /* cleanup the saved copy of module dicts */ PyModuleDef *md = PyModule_GetDef(m); if (md) Py_CLEAR(md->m_base.m_copy); } } /* Setting modules_by_index to NULL could be dangerous, so we clear the list instead. */ if (PyList_SetSlice(state->modules_by_index, 0, PyList_GET_SIZE(state->modules_by_index), NULL)) PyErr_WriteUnraisable(state->modules_by_index); } } void PyThreadState_Clear(PyThreadState *tstate) { if (Py_VerboseFlag && tstate->frame != NULL) fprintf(stderr, "PyThreadState_Clear: warning: thread still has a frame\n"); Py_CLEAR(tstate->frame); Py_CLEAR(tstate->dict); Py_CLEAR(tstate->async_exc); Py_CLEAR(tstate->curexc_type); Py_CLEAR(tstate->curexc_value); Py_CLEAR(tstate->curexc_traceback); Py_CLEAR(tstate->exc_type); Py_CLEAR(tstate->exc_value); Py_CLEAR(tstate->exc_traceback); tstate->c_profilefunc = NULL; tstate->c_tracefunc = NULL; Py_CLEAR(tstate->c_profileobj); Py_CLEAR(tstate->c_traceobj); Py_CLEAR(tstate->coroutine_wrapper); Py_CLEAR(tstate->async_gen_firstiter); Py_CLEAR(tstate->async_gen_finalizer); } /* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */ static void tstate_delete_common(PyThreadState *tstate) { PyInterpreterState *interp; if (tstate == NULL) Py_FatalError("PyThreadState_Delete: NULL tstate"); interp = tstate->interp; if (interp == NULL) Py_FatalError("PyThreadState_Delete: NULL interp"); HEAD_LOCK(); if (tstate->prev) tstate->prev->next = tstate->next; else interp->tstate_head = tstate->next; if (tstate->next) tstate->next->prev = tstate->prev; HEAD_UNLOCK(); if (tstate->on_delete != NULL) { tstate->on_delete(tstate->on_delete_data); } PyMem_RawFree(tstate); } void PyThreadState_Delete(PyThreadState *tstate) { if (tstate == GET_TSTATE()) Py_FatalError("PyThreadState_Delete: tstate is still current"); #ifdef WITH_THREAD if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate) PyThread_delete_key_value(autoTLSkey); #endif /* WITH_THREAD */ tstate_delete_common(tstate); } #ifdef WITH_THREAD void PyThreadState_DeleteCurrent() { PyThreadState *tstate = GET_TSTATE(); if (tstate == NULL) Py_FatalError( "PyThreadState_DeleteCurrent: no current tstate"); tstate_delete_common(tstate); if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate) PyThread_delete_key_value(autoTLSkey); SET_TSTATE(NULL); PyEval_ReleaseLock(); } #endif /* WITH_THREAD */ /* * Delete all thread states except the one passed as argument. * Note that, if there is a current thread state, it *must* be the one * passed as argument. Also, this won't touch any other interpreters * than the current one, since we don't know which thread state should * be kept in those other interpreteres. */ void _PyThreadState_DeleteExcept(PyThreadState *tstate) { PyInterpreterState *interp = tstate->interp; PyThreadState *p, *next, *garbage; HEAD_LOCK(); /* Remove all thread states, except tstate, from the linked list of thread states. This will allow calling PyThreadState_Clear() without holding the lock. */ garbage = interp->tstate_head; if (garbage == tstate) garbage = tstate->next; if (tstate->prev) tstate->prev->next = tstate->next; if (tstate->next) tstate->next->prev = tstate->prev; tstate->prev = tstate->next = NULL; interp->tstate_head = tstate; HEAD_UNLOCK(); /* Clear and deallocate all stale thread states. Even if this executes Python code, we should be safe since it executes in the current thread, not one of the stale threads. */ for (p = garbage; p; p = next) { next = p->next; PyThreadState_Clear(p); PyMem_RawFree(p); } } PyThreadState * (_PyThreadState_UncheckedGet)(void) { return GET_TSTATE(); } PyThreadState * PyThreadState_Get(void) { PyThreadState *tstate = GET_TSTATE(); if (tstate == NULL) Py_FatalError("PyThreadState_Get: no current thread"); return tstate; } PyThreadState * PyThreadState_Swap(PyThreadState *newts) { PyThreadState *oldts = GET_TSTATE(); SET_TSTATE(newts); /* It should not be possible for more than one thread state to be used for a thread. Check this the best we can in debug builds. */ #if defined(Py_DEBUG) && defined(WITH_THREAD) if (newts) { /* This can be called from PyEval_RestoreThread(). Similar to it, we need to ensure errno doesn't change. */ int err = errno; PyThreadState *check = PyGILState_GetThisThreadState(); if (check && check->interp == newts->interp && check != newts) Py_FatalError("Invalid thread state for this thread"); errno = err; } #endif return oldts; } __PyCodeExtraState* __PyCodeExtraState_Get(void) { PyInterpreterState* interp = PyThreadState_Get()->interp; HEAD_LOCK(); for (__PyCodeExtraState* cur = coextra_head; cur != NULL; cur = cur->next) { if (cur->interp == interp) { HEAD_UNLOCK(); return cur; } } HEAD_UNLOCK(); Py_FatalError("__PyCodeExtraState_Get: no code state for interpreter"); return NULL; } /* An extension mechanism to store arbitrary additional per-thread state. PyThreadState_GetDict() returns a dictionary that can be used to hold such state; the caller should pick a unique key and store its state there. If PyThreadState_GetDict() returns NULL, an exception has *not* been raised and the caller should assume no per-thread state is available. */ PyObject * PyThreadState_GetDict(void) { PyThreadState *tstate = GET_TSTATE(); if (tstate == NULL) return NULL; if (tstate->dict == NULL) { PyObject *d; tstate->dict = d = PyDict_New(); if (d == NULL) PyErr_Clear(); } return tstate->dict; } /* Asynchronously raise an exception in a thread. Requested by Just van Rossum and Alex Martelli. To prevent naive misuse, you must write your own extension to call this, or use ctypes. Must be called with the GIL held. Returns the number of tstates modified (normally 1, but 0 if `id` didn't match any known thread id). Can be called with exc=NULL to clear an existing async exception. This raises no exceptions. */ int PyThreadState_SetAsyncExc(long id, PyObject *exc) { PyInterpreterState *interp = GET_INTERP_STATE(); PyThreadState *p; /* Although the GIL is held, a few C API functions can be called * without the GIL held, and in particular some that create and * destroy thread and interpreter states. Those can mutate the * list of thread states we're traversing, so to prevent that we lock * head_mutex for the duration. */ HEAD_LOCK(); for (p = interp->tstate_head; p != NULL; p = p->next) { if (p->thread_id == id) { /* Tricky: we need to decref the current value * (if any) in p->async_exc, but that can in turn * allow arbitrary Python code to run, including * perhaps calls to this function. To prevent * deadlock, we need to release head_mutex before * the decref. */ PyObject *old_exc = p->async_exc; Py_XINCREF(exc); p->async_exc = exc; HEAD_UNLOCK(); Py_XDECREF(old_exc); _PyEval_SignalAsyncExc(); return 1; } } HEAD_UNLOCK(); return 0; } /* Routines for advanced debuggers, requested by David Beazley. Don't use unless you know what you are doing! */ PyInterpreterState * PyInterpreterState_Head(void) { return interp_head; } PyInterpreterState * PyInterpreterState_Next(PyInterpreterState *interp) { return interp->next; } PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp) { return interp->tstate_head; } PyThreadState * PyThreadState_Next(PyThreadState *tstate) { return tstate->next; } /* The implementation of sys._current_frames(). This is intended to be called with the GIL held, as it will be when called via sys._current_frames(). It's possible it would work fine even without the GIL held, but haven't thought enough about that. */ PyObject * _PyThread_CurrentFrames(void) { PyObject *result; PyInterpreterState *i; result = PyDict_New(); if (result == NULL) return NULL; /* for i in all interpreters: * for t in all of i's thread states: * if t's frame isn't NULL, map t's id to its frame * Because these lists can mutate even when the GIL is held, we * need to grab head_mutex for the duration. */ HEAD_LOCK(); for (i = interp_head; i != NULL; i = i->next) { PyThreadState *t; for (t = i->tstate_head; t != NULL; t = t->next) { PyObject *id; int stat; struct _frame *frame = t->frame; if (frame == NULL) continue; id = PyLong_FromLong(t->thread_id); if (id == NULL) goto Fail; stat = PyDict_SetItem(result, id, (PyObject *)frame); Py_DECREF(id); if (stat < 0) goto Fail; } } HEAD_UNLOCK(); return result; Fail: HEAD_UNLOCK(); Py_DECREF(result); return NULL; } /* Python "auto thread state" API. */ #ifdef WITH_THREAD /* Keep this as a static, as it is not reliable! It can only ever be compared to the state for the *current* thread. * If not equal, then it doesn't matter that the actual value may change immediately after comparison, as it can't possibly change to the current thread's state. * If equal, then the current thread holds the lock, so the value can't change until we yield the lock. */ static int PyThreadState_IsCurrent(PyThreadState *tstate) { /* Must be the tstate for this thread */ assert(PyGILState_GetThisThreadState()==tstate); return tstate == GET_TSTATE(); } /* Internal initialization/finalization functions called by Py_Initialize/Py_FinalizeEx */ void _PyGILState_Init(PyInterpreterState *i, PyThreadState *t) { assert(i && t); /* must init with valid states */ autoTLSkey = PyThread_create_key(); if (autoTLSkey == -1) Py_FatalError("Could not allocate TLS entry"); autoInterpreterState = i; assert(PyThread_get_key_value(autoTLSkey) == NULL); assert(t->gilstate_counter == 0); _PyGILState_NoteThreadState(t); } PyInterpreterState * _PyGILState_GetInterpreterStateUnsafe(void) { return autoInterpreterState; } void _PyGILState_Fini(void) { PyThread_delete_key(autoTLSkey); autoTLSkey = -1; autoInterpreterState = NULL; } /* Reset the TLS key - called by PyOS_AfterFork(). * This should not be necessary, but some - buggy - pthread implementations * don't reset TLS upon fork(), see issue #10517. */ void _PyGILState_Reinit(void) { #ifdef WITH_THREAD head_mutex = NULL; HEAD_INIT(); #endif PyThreadState *tstate = PyGILState_GetThisThreadState(); PyThread_delete_key(autoTLSkey); if ((autoTLSkey = PyThread_create_key()) == -1) Py_FatalError("Could not allocate TLS entry"); /* If the thread had an associated auto thread state, reassociate it with * the new key. */ if (tstate && PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0) Py_FatalError("Couldn't create autoTLSkey mapping"); } /* When a thread state is created for a thread by some mechanism other than PyGILState_Ensure, it's important that the GILState machinery knows about it so it doesn't try to create another thread state for the thread (this is a better fix for SF bug #1010677 than the first one attempted). */ static void _PyGILState_NoteThreadState(PyThreadState* tstate) { /* If autoTLSkey isn't initialized, this must be the very first threadstate created in Py_Initialize(). Don't do anything for now (we'll be back here when _PyGILState_Init is called). */ if (!autoInterpreterState) return; /* Stick the thread state for this thread in thread local storage. The only situation where you can legitimately have more than one thread state for an OS level thread is when there are multiple interpreters. You shouldn't really be using the PyGILState_ APIs anyway (see issues #10915 and #15751). The first thread state created for that given OS level thread will "win", which seems reasonable behaviour. */ if (PyThread_get_key_value(autoTLSkey) == NULL) { if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0) Py_FatalError("Couldn't create autoTLSkey mapping"); } /* PyGILState_Release must not try to delete this thread state. */ tstate->gilstate_counter = 1; } /* The public functions */ PyThreadState * PyGILState_GetThisThreadState(void) { if (autoInterpreterState == NULL) return NULL; return (PyThreadState *)PyThread_get_key_value(autoTLSkey); } int PyGILState_Check(void) { PyThreadState *tstate; if (!_PyGILState_check_enabled) return 1; if (autoTLSkey == -1) return 1; tstate = GET_TSTATE(); if (tstate == NULL) return 0; return (tstate == PyGILState_GetThisThreadState()); } PyGILState_STATE PyGILState_Ensure(void) { int current; PyThreadState *tcur; int need_init_threads = 0; /* Note that we do not auto-init Python here - apart from potential races with 2 threads auto-initializing, pep-311 spells out other issues. Embedders are expected to have called Py_Initialize() and usually PyEval_InitThreads(). */ assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */ tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey); if (tcur == NULL) { need_init_threads = 1; /* Create a new thread state for this thread */ tcur = PyThreadState_New(autoInterpreterState); if (tcur == NULL) Py_FatalError("Couldn't create thread-state for new thread"); /* This is our thread state! We'll need to delete it in the matching call to PyGILState_Release(). */ tcur->gilstate_counter = 0; current = 0; /* new thread state is never current */ } else { current = PyThreadState_IsCurrent(tcur); } if (current == 0) { PyEval_RestoreThread(tcur); } /* Update our counter in the thread-state - no need for locks: - tcur will remain valid as we hold the GIL. - the counter is safe as we are the only thread "allowed" to modify this value */ ++tcur->gilstate_counter; if (need_init_threads) { /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is called from a new thread for the first time, we need the create the GIL. */ PyEval_InitThreads(); } return current ? PyGILState_LOCKED : PyGILState_UNLOCKED; } void PyGILState_Release(PyGILState_STATE oldstate) { PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value( autoTLSkey); if (tcur == NULL) Py_FatalError("auto-releasing thread-state, " "but no thread-state for this thread"); /* We must hold the GIL and have our thread state current */ /* XXX - remove the check - the assert should be fine, but while this is very new (April 2003), the extra check by release-only users can't hurt. */ if (! PyThreadState_IsCurrent(tcur)) Py_FatalError("This thread state must be current when releasing"); assert(PyThreadState_IsCurrent(tcur)); --tcur->gilstate_counter; assert(tcur->gilstate_counter >= 0); /* illegal counter value */ /* If we're going to destroy this thread-state, we must * clear it while the GIL is held, as destructors may run. */ if (tcur->gilstate_counter == 0) { /* can't have been locked when we created it */ assert(oldstate == PyGILState_UNLOCKED); PyThreadState_Clear(tcur); /* Delete the thread-state. Note this releases the GIL too! * It's vital that the GIL be held here, to avoid shutdown * races; see bugs 225673 and 1061968 (that nasty bug has a * habit of coming back). */ PyThreadState_DeleteCurrent(); } /* Release the lock if necessary */ else if (oldstate == PyGILState_UNLOCKED) PyEval_SaveThread(); } #endif /* WITH_THREAD */
29,435
950
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/random.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/calls/weirdtypes.h" #include "libc/errno.h" #include "libc/fmt/conv.h" #include "libc/macros.internal.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/stdio/rand.h" #include "libc/runtime/runtime.h" #include "libc/str/str.h" #include "libc/sysv/consts/auxv.h" #include "libc/sysv/consts/grnd.h" #include "libc/sysv/consts/o.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyhash.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/pyconfig.h" /* clang-format off */ #ifdef Py_DEBUG int _Py_HashSecret_Initialized = 0; #else static int _Py_HashSecret_Initialized = 0; #endif #define PY_GETRANDOM 1 /* Call getrandom() to get random bytes: - Return 1 on success - Return 0 if getrandom() is not available (failed with ENOSYS or EPERM), or if getrandom(GRND_NONBLOCK) failed with EAGAIN (system urandom not initialized yet) and raise=0. - Raise an exception (if raise is non-zero) and return -1 on error: if getrandom() failed with EINTR, raise is non-zero and the Python signal handler raised an exception, or if getrandom() failed with a different error. getrandom() is retried if it failed with EINTR: interrupted by a signal. */ static int py_getrandom(void *buffer, Py_ssize_t size, int blocking, int raise) { /* Is getrandom() supported by the running kernel? Set to 0 if getrandom() failed with ENOSYS or EPERM. Need Linux kernel 3.17 or newer, or Solaris 11.3 or newer */ static int getrandom_works = 1; int flags; char *dest; long n; if (!getrandom_works) { return 0; } flags = blocking ? 0 : GRND_NONBLOCK; dest = buffer; while (0 < size) { n = Py_MIN(size, 256); errno = 0; if (raise) { Py_BEGIN_ALLOW_THREADS n = getrandom(dest, n, flags); Py_END_ALLOW_THREADS } else { n = getrandom(dest, n, flags); } if (n < 0) { /* ENOSYS: the syscall is not supported by the kernel. EPERM: the syscall is blocked by a security policy (ex: SECCOMP) or something else. */ if (errno == ENOSYS || errno == EPERM) { getrandom_works = 0; return 0; } /* getrandom(GRND_NONBLOCK) fails with EAGAIN if the system urandom is not initialiazed yet. For _PyRandom_Init(), we ignore the error and fall back on reading /dev/urandom which never blocks, even if the system urandom is not initialized yet: see the PEP 524. */ if (errno == EAGAIN && !raise && !blocking) { return 0; } if (errno == EINTR) { if (raise) { if (PyErr_CheckSignals()) { return -1; } } /* retry getrandom() if it was interrupted by a signal */ continue; } if (raise) { PyErr_SetFromErrno(PyExc_OSError); } return -1; } dest += n; size -= n; } return 1; } static struct { int fd; dev_t st_dev; ino_t st_ino; } urandom_cache = { -1 }; /* Read random bytes from the /dev/urandom device: - Return 0 on success - Raise an exception (if raise is non-zero) and return -1 on error Possible causes of errors: - open() failed with ENOENT, ENXIO, ENODEV, EACCES: the /dev/urandom device was not found. For example, it was removed manually or not exposed in a chroot or container. - open() failed with a different error - fstat() failed - read() failed or returned 0 read() is retried if it failed with EINTR: interrupted by a signal. The file descriptor of the device is kept open between calls to avoid using many file descriptors when run in parallel from multiple threads: see the issue #18756. st_dev and st_ino fields of the file descriptor (from fstat()) are cached to check if the file descriptor was replaced by a different file (which is likely a bug in the application): see the issue #21207. If the file descriptor was closed or replaced, open a new file descriptor but don't close the old file descriptor: it probably points to something important for some third-party code. */ static int dev_urandom(char *buffer, Py_ssize_t size, int raise) { int fd; Py_ssize_t n; if (raise) { struct _Py_stat_struct st; int fstat_result; if (urandom_cache.fd >= 0) { Py_BEGIN_ALLOW_THREADS fstat_result = _Py_fstat_noraise(urandom_cache.fd, &st); Py_END_ALLOW_THREADS /* Does the fd point to the same thing as before? (issue #21207) */ if (fstat_result || st.st_dev != urandom_cache.st_dev || st.st_ino != urandom_cache.st_ino) { /* Something changed: forget the cached fd (but don't close it, since it probably points to something important for some third-party code). */ urandom_cache.fd = -1; } } if (urandom_cache.fd >= 0) fd = urandom_cache.fd; else { fd = _Py_open("/dev/urandom", O_RDONLY); if (fd < 0) { if (errno == ENOENT || errno == ENXIO || errno == ENODEV || errno == EACCES) { PyErr_SetString(PyExc_NotImplementedError, "/dev/urandom (or equivalent) not found"); } /* otherwise, keep the OSError exception raised by _Py_open() */ return -1; } if (urandom_cache.fd >= 0) { /* urandom_fd was initialized by another thread while we were not holding the GIL, keep it. */ close(fd); fd = urandom_cache.fd; } else { if (_Py_fstat(fd, &st)) { close(fd); return -1; } else { urandom_cache.fd = fd; urandom_cache.st_dev = st.st_dev; urandom_cache.st_ino = st.st_ino; } } } do { n = _Py_read(fd, buffer, (size_t)size); if (n == -1) return -1; if (n == 0) { PyErr_Format(PyExc_RuntimeError, "Failed to read %zi bytes from /dev/urandom", size); return -1; } buffer += n; size -= n; } while (0 < size); } else { fd = _Py_open_noraise("/dev/urandom", O_RDONLY); if (fd < 0) { return -1; } while (0 < size) { do { n = read(fd, buffer, (size_t)size); } while (n < 0 && errno == EINTR); if (n <= 0) { /* stop on error or if read(size) returned 0 */ close(fd); return -1; } buffer += n; size -= n; } close(fd); } return 0; } static void dev_urandom_close(void) { if (urandom_cache.fd >= 0) { close(urandom_cache.fd); urandom_cache.fd = -1; } } /* Fill buffer with pseudo-random bytes generated by a linear congruent generator (LCG): x(n+1) = (x(n) * 214013 + 2531011) % 2^32 Use bits 23..16 of x(n) to generate a byte. */ static void lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size) { size_t index; unsigned int x; x = x0; for (index=0; index < size; index++) { x *= 214013; x += 2531011; /* modulo 2 ^ (8 * sizeof(int)) */ buffer[index] = (x >> 16) & 0xff; } } /* Read random bytes: - Return 0 on success - Raise an exception (if raise is non-zero) and return -1 on error Used sources of entropy ordered by preference: - getrandom() Read from the /dev/urandom device if getrandom() or getentropy() function is not available or does not work. Prefer getrandom() over getentropy() because getrandom() supports blocking and non-blocking mode: see the PEP 524. Python requires non-blocking RNG at startup to initialize its hash secret, but os.urandom() must block until the system urandom is initialized (at least on Linux 3.17 and newer). Prefer getrandom() and getentropy() over reading directly /dev/urandom because these functions don't need file descriptors and so avoid ENFILE or EMFILE errors (too many open files): see the issue #18756. Only the getrandom() function supports non-blocking mode. Only use RNG running in the kernel. They are more secure because it is harder to get the internal state of a RNG running in the kernel land than a RNG running in the user land. The kernel has a direct access to the hardware and has access to hardware RNG, they are used as entropy sources. Note: the OpenSSL RAND_pseudo_bytes() function does not automatically reseed its RNG on fork(), two child processes (with the same pid) generate the same random numbers: see issue #18747. Kernel RNGs don't have this issue, they have access to good quality entropy sources. If raise is zero: - Don't raise an exception on error - Don't call the Python signal handler (don't call PyErr_CheckSignals()) if a function fails with EINTR: retry directly the interrupted function - Don't release the GIL to call functions. */ static int pyurandom(void *buffer, Py_ssize_t size, int blocking, int raise) { #if defined(PY_GETRANDOM) || defined(PY_GETENTROPY) int res; #endif if (size < 0) { if (raise) { PyErr_Format(PyExc_ValueError, "negative argument not allowed"); } return -1; } if (size == 0) { return 0; } #ifdef MS_WINDOWS return win32_urandom((unsigned char *)buffer, size, raise); #else #if defined(PY_GETRANDOM) || defined(PY_GETENTROPY) res = py_getrandom(buffer, size, blocking, raise); if (res < 0) { return -1; } if (res == 1) { return 0; } /* getrandom() or getentropy() function is not available: failed with ENOSYS or EPERM. Fall back on reading from /dev/urandom. */ #endif return dev_urandom(buffer, size, raise); #endif } /* Fill buffer with size pseudo-random bytes from the operating system random number generator (RNG). It is suitable for most cryptographic purposes except long living private keys for asymmetric encryption. On Linux 3.17 and newer, the getrandom() syscall is used in blocking mode: block until the system urandom entropy pool is initialized (128 bits are collected by the kernel). Return 0 on success. Raise an exception and return -1 on error. */ int _PyOS_URandom(void *buffer, Py_ssize_t size) { return pyurandom(buffer, size, 1, 1); } /* Fill buffer with size pseudo-random bytes from the operating system random number generator (RNG). It is not suitable for cryptographic purpose. On Linux 3.17 and newer (when getrandom() syscall is used), if the system urandom is not initialized yet, the function returns "weak" entropy read from /dev/urandom. Return 0 on success. Raise an exception and return -1 on error. */ int _PyOS_URandomNonblock(void *buffer, Py_ssize_t size) { return pyurandom(buffer, size, 0, 1); } void _PyRandom_Init(void) { char *env; const unsigned char *auxrng; unsigned char *secret = (unsigned char *)&_Py_HashSecret.uc; Py_ssize_t secret_size = sizeof(_Py_HashSecret_t); Py_BUILD_ASSERT(sizeof(_Py_HashSecret_t) == sizeof(_Py_HashSecret.uc)); _Static_assert(sizeof(_Py_HashSecret_t) == 24, ""); if (_Py_HashSecret_Initialized) return; _Py_HashSecret_Initialized = 1; /* Hash randomization is enabled. Generate a per-process secret, using PYTHONHASHSEED if provided. */ env = Py_GETENV("PYTHONHASHSEED"); if (env && *env != '\0' && strcmp(env, "random") != 0) { char *endptr = env; unsigned long seed; seed = strtoul(env, &endptr, 10); if (*endptr != '\0' || seed > 4294967295UL || (errno == ERANGE && seed == ULONG_MAX)) { Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer " "in range [0; 4294967295]"); } if (seed == 0) { /* disable the randomized hash */ bzero(secret, secret_size); Py_HashRandomizationFlag = 0; } else { lcg_urandom(seed, secret, secret_size); Py_HashRandomizationFlag = 1; } } else { uint64_t x; int res, i, j; /* _PyRandom_Init() is called very early in the Python initialization and so exceptions cannot be used (use raise=0). _PyRandom_Init() must not block Python initialization: call pyurandom() is non-blocking mode (blocking=0): see the PEP 524. */ #if 1 /* * [jart] modified to be more efficient */ for (i = 0; i < secret_size;) { x = rdrand(); // will failover to getrandom() etc. for (j = 0; j < 8; ++j) { if (i < secret_size) { secret[i++] = x; x >>= 8; } } } #else res = pyurandom(secret, secret_size, 0, 0); if (res < 0) { Py_FatalError("failed to get random numbers to initialize Python"); } #endif Py_HashRandomizationFlag = 1; } } void _PyRandom_Fini(void) { #ifdef MS_WINDOWS if (hCryptProv) { CryptReleaseContext(hCryptProv, 0); hCryptProv = 0; } #else dev_urandom_close(); #endif }
15,211
474
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pythonrun.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/stdio/stdio.h" #include "libc/str/locale.h" #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/ast.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/errcode.h" #include "third_party/python/Include/eval.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/marshal.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/osdefs.h" #include "third_party/python/Include/parsetok.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/symtable.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/token.h" #include "third_party/python/Include/traceback.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ /* Python interpreter top-level routines, including init/exit */ _Py_IDENTIFIER(builtins); _Py_IDENTIFIER(excepthook); _Py_IDENTIFIER(flush); _Py_IDENTIFIER(last_traceback); _Py_IDENTIFIER(last_type); _Py_IDENTIFIER(last_value); _Py_IDENTIFIER(ps1); _Py_IDENTIFIER(ps2); _Py_IDENTIFIER(stdin); _Py_IDENTIFIER(stdout); _Py_IDENTIFIER(stderr); _Py_static_string(PyId_string, "<string>"); extern grammar _PyParser_Grammar; /* From graminit.c */ /* Forward */ static void flush_io(void); static PyObject *run_mod(mod_ty, PyObject *, PyObject *, PyObject *, PyCompilerFlags *, PyArena *); static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *, PyCompilerFlags *); static void err_input(perrdetail *); static void err_free(perrdetail *); static int PyRun_InteractiveOneObjectEx(FILE *, PyObject *, PyCompilerFlags *); /* Parse input from a file and execute it */ int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) { if (filename == NULL) filename = "???"; if (Py_FdIsInteractive(fp, filename)) { int err = PyRun_InteractiveLoopFlags(fp, filename, flags); if (closeit) fclose(fp); return err; } else return PyRun_SimpleFileExFlags(fp, filename, closeit, flags); } int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags) { PyObject *filename, *v; int ret, err; PyCompilerFlags local_flags; int nomem_count = 0; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) { PyErr_Print(); return -1; } if (flags == NULL) { flags = &local_flags; local_flags.cf_flags = 0; } v = _PySys_GetObjectId(&PyId_ps1); if (v == NULL) { _PySys_SetObjectId(&PyId_ps1, v = PyUnicode_FromString(">>: ")); Py_XDECREF(v); } v = _PySys_GetObjectId(&PyId_ps2); if (v == NULL) { _PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... ")); Py_XDECREF(v); } err = 0; do { ret = PyRun_InteractiveOneObjectEx(fp, filename, flags); if (ret == -1 && PyErr_Occurred()) { /* Prevent an endless loop after multiple consecutive MemoryErrors * while still allowing an interactive command to fail with a * MemoryError. */ if (PyErr_ExceptionMatches(PyExc_MemoryError)) { if (++nomem_count > 16) { PyErr_Clear(); err = -1; break; } } else { nomem_count = 0; } PyErr_Print(); flush_io(); } else { nomem_count = 0; } _PY_DEBUG_PRINT_TOTAL_REFS(); } while (ret != E_EOF); Py_DECREF(filename); return err; } /* compute parser flags based on compiler flags */ static int PARSER_FLAGS(PyCompilerFlags *flags) { int parser_flags = 0; if (!flags) return 0; if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT) parser_flags |= PyPARSE_DONT_IMPLY_DEDENT; if (flags->cf_flags & PyCF_IGNORE_COOKIE) parser_flags |= PyPARSE_IGNORE_COOKIE; if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL) parser_flags |= PyPARSE_BARRY_AS_BDFL; return parser_flags; } #if 0 /* Keep an example of flags with future keyword support. */ #define PARSER_FLAGS(flags) \ ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \ PyPARSE_DONT_IMPLY_DEDENT : 0) \ | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \ PyPARSE_WITH_IS_KEYWORD : 0)) : 0) #endif /* A PyRun_InteractiveOneObject() auxiliary function that does not print the * error on failure. */ static int PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename, PyCompilerFlags *flags) { PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name; mod_ty mod; PyArena *arena; char *ps1 = "", *ps2 = "", *enc = NULL; int errcode = 0; _Py_IDENTIFIER(encoding); _Py_IDENTIFIER(__main__); mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */ if (mod_name == NULL) { return -1; } if (fp == stdin) { /* Fetch encoding from sys.stdin if possible. */ v = _PySys_GetObjectId(&PyId_stdin); if (v && v != Py_None) { oenc = _PyObject_GetAttrId(v, &PyId_encoding); if (oenc) enc = PyUnicode_AsUTF8(oenc); if (!enc) PyErr_Clear(); } } v = _PySys_GetObjectId(&PyId_ps1); if (v != NULL) { v = PyObject_Str(v); if (v == NULL) PyErr_Clear(); else if (PyUnicode_Check(v)) { ps1 = PyUnicode_AsUTF8(v); if (ps1 == NULL) { PyErr_Clear(); ps1 = ""; } } } w = _PySys_GetObjectId(&PyId_ps2); if (w != NULL) { w = PyObject_Str(w); if (w == NULL) PyErr_Clear(); else if (PyUnicode_Check(w)) { ps2 = PyUnicode_AsUTF8(w); if (ps2 == NULL) { PyErr_Clear(); ps2 = ""; } } } arena = PyArena_New(); if (arena == NULL) { Py_XDECREF(v); Py_XDECREF(w); Py_XDECREF(oenc); return -1; } mod = PyParser_ASTFromFileObject(fp, filename, enc, Py_single_input, ps1, ps2, flags, &errcode, arena); Py_XDECREF(v); Py_XDECREF(w); Py_XDECREF(oenc); if (mod == NULL) { PyArena_Free(arena); if (errcode == E_EOF) { PyErr_Clear(); return E_EOF; } return -1; } m = PyImport_AddModuleObject(mod_name); if (m == NULL) { PyArena_Free(arena); return -1; } d = PyModule_GetDict(m); v = run_mod(mod, filename, d, d, flags, arena); PyArena_Free(arena); if (v == NULL) { return -1; } Py_DECREF(v); flush_io(); return 0; } int PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags) { int res; res = PyRun_InteractiveOneObjectEx(fp, filename, flags); if (res == -1) { PyErr_Print(); flush_io(); } return res; } int PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags) { PyObject *filename; int res; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) { PyErr_Print(); return -1; } res = PyRun_InteractiveOneObject(fp, filename, flags); Py_DECREF(filename); return res; } /* Check whether a file maybe a pyc file: Look at the extension, the file type, and, if we may close it, at the first few bytes. */ static int maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit) { if (strcmp(ext, ".pyc") == 0) return 1; /* Only look into the file if we are allowed to close it, since it then should also be seekable. */ if (closeit) { /* Read only two bytes of the magic. If the file was opened in text mode, the bytes 3 and 4 of the magic (\r\n) might not be read as they are on disk. */ unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF; unsigned char buf[2]; /* Mess: In case of -x, the stream is NOT at its start now, and ungetc() was used to push back the first newline, which makes the current stream position formally undefined, and a x-platform nightmare. Unfortunately, we have no direct way to know whether -x was specified. So we use a terrible hack: if the current stream position is not 0, we assume -x was specified, and give up. Bug 132850 on SourceForge spells out the hopelessness of trying anything else (fseek and ftell don't work predictably x-platform for text-mode files). */ int ispyc = 0; if (ftell(fp) == 0) { if (fread(buf, 1, 2, fp) == 2 && ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic) ispyc = 1; rewind(fp); } return ispyc; } return 0; } static int set_main_loader(PyObject *d, const char *filename, const char *loader_name) { PyInterpreterState *interp; PyThreadState *tstate; PyObject *filename_obj, *bootstrap, *loader_type = NULL, *loader; int result = 0; filename_obj = PyUnicode_DecodeFSDefault(filename); if (filename_obj == NULL) return -1; /* Get current thread state and interpreter pointer */ tstate = PyThreadState_GET(); interp = tstate->interp; bootstrap = PyObject_GetAttrString(interp->importlib, "_bootstrap_external"); if (bootstrap != NULL) { loader_type = PyObject_GetAttrString(bootstrap, loader_name); Py_DECREF(bootstrap); } if (loader_type == NULL) { Py_DECREF(filename_obj); return -1; } loader = PyObject_CallFunction(loader_type, "sN", "__main__", filename_obj); Py_DECREF(loader_type); if (loader == NULL) { return -1; } if (PyDict_SetItemString(d, "__loader__", loader) < 0) { result = -1; } Py_DECREF(loader); return result; } int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) { PyObject *m, *d, *v; const char *ext; int set_file_name = 0, ret = -1; size_t len; m = PyImport_AddModule("__main__"); if (m == NULL) return -1; Py_INCREF(m); d = PyModule_GetDict(m); if (PyDict_GetItemString(d, "__file__") == NULL) { PyObject *f; f = PyUnicode_DecodeFSDefault(filename); if (f == NULL) goto done; if (PyDict_SetItemString(d, "__file__", f) < 0) { Py_DECREF(f); goto done; } if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) { Py_DECREF(f); goto done; } set_file_name = 1; Py_DECREF(f); } len = strlen(filename); ext = filename + len - (len > 4 ? 4 : 0); if (maybe_pyc_file(fp, filename, ext, closeit)) { FILE *pyc_fp; /* Try to run a pyc file. First, re-open in binary */ if (closeit) fclose(fp); if ((pyc_fp = _Py_fopen(filename, "rb")) == NULL) { fprintf(stderr, "python: Can't reopen .pyc file\n"); goto done; } if (set_main_loader(d, filename, "SourcelessFileLoader") < 0) { fprintf(stderr, "python: failed to set __main__.__loader__\n"); ret = -1; fclose(pyc_fp); goto done; } v = run_pyc_file(pyc_fp, filename, d, d, flags); } else { /* When running from stdin, leave __main__.__loader__ alone */ if (strcmp(filename, "<stdin>") != 0 && set_main_loader(d, filename, "SourceFileLoader") < 0) { fprintf(stderr, "python: failed to set __main__.__loader__\n"); ret = -1; goto done; } v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d, closeit, flags); } flush_io(); if (v == NULL) { Py_CLEAR(m); PyErr_Print(); goto done; } Py_DECREF(v); ret = 0; done: if (set_file_name && PyDict_DelItemString(d, "__file__")) PyErr_Clear(); Py_XDECREF(m); return ret; } int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) { PyObject *m, *d, *v; m = PyImport_AddModule("__main__"); if (m == NULL) return -1; d = PyModule_GetDict(m); v = PyRun_StringFlags(command, Py_file_input, d, d, flags); if (v == NULL) { PyErr_Print(); return -1; } Py_DECREF(v); return 0; } static int parse_syntax_error(PyObject *err, PyObject **message, PyObject **filename, int *lineno, int *offset, PyObject **text) { int hold; PyObject *v; _Py_IDENTIFIER(msg); _Py_IDENTIFIER(filename); _Py_IDENTIFIER(lineno); _Py_IDENTIFIER(offset); _Py_IDENTIFIER(text); *message = NULL; *filename = NULL; /* new style errors. `err' is an instance */ *message = _PyObject_GetAttrId(err, &PyId_msg); if (!*message) goto finally; v = _PyObject_GetAttrId(err, &PyId_filename); if (!v) goto finally; if (v == Py_None) { Py_DECREF(v); *filename = _PyUnicode_FromId(&PyId_string); if (*filename == NULL) goto finally; Py_INCREF(*filename); } else { *filename = v; } v = _PyObject_GetAttrId(err, &PyId_lineno); if (!v) goto finally; hold = _PyLong_AsInt(v); Py_DECREF(v); if (hold < 0 && PyErr_Occurred()) goto finally; *lineno = hold; v = _PyObject_GetAttrId(err, &PyId_offset); if (!v) goto finally; if (v == Py_None) { *offset = -1; Py_DECREF(v); } else { hold = _PyLong_AsInt(v); Py_DECREF(v); if (hold < 0 && PyErr_Occurred()) goto finally; *offset = hold; } v = _PyObject_GetAttrId(err, &PyId_text); if (!v) goto finally; if (v == Py_None) { Py_DECREF(v); *text = NULL; } else { *text = v; } return 1; finally: Py_XDECREF(*message); Py_XDECREF(*filename); return 0; } void PyErr_Print(void) { PyErr_PrintEx(1); } static void print_error_text(PyObject *f, int offset, PyObject *text_obj) { char *text; char *nl; text = PyUnicode_AsUTF8(text_obj); if (text == NULL) return; if (offset >= 0) { if (offset > 0 && (size_t)offset == strlen(text) && text[offset - 1] == '\n') offset--; for (;;) { nl = strchr(text, '\n'); if (nl == NULL || nl-text >= offset) break; offset -= (int)(nl+1-text); text = nl+1; } while (*text == ' ' || *text == '\t' || *text == '\f') { text++; offset--; } } PyFile_WriteString(" ", f); PyFile_WriteString(text, f); if (*text == '\0' || text[strlen(text)-1] != '\n') PyFile_WriteString("\n", f); if (offset == -1) return; PyFile_WriteString(" ", f); while (--offset > 0) PyFile_WriteString(" ", f); PyFile_WriteString("^\n", f); } static void handle_system_exit(void) { PyObject *exception, *value, *tb; int exitcode = 0; if (Py_InspectFlag) /* Don't exit if -i flag was given. This flag is set to 0 * when entering interactive mode for inspecting. */ return; PyErr_Fetch(&exception, &value, &tb); fflush(stdout); if (value == NULL || value == Py_None) goto done; if (PyExceptionInstance_Check(value)) { /* The error code should be in the `code' attribute. */ _Py_IDENTIFIER(code); PyObject *code = _PyObject_GetAttrId(value, &PyId_code); if (code) { Py_DECREF(value); value = code; if (value == Py_None) goto done; } /* If we failed to dig out the 'code' attribute, just let the else clause below print the error. */ } if (PyLong_Check(value)) exitcode = (int)PyLong_AsLong(value); else { PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr); /* We clear the exception here to avoid triggering the assertion * in PyObject_Str that ensures it won't silently lose exception * details. */ PyErr_Clear(); if (sys_stderr != NULL && sys_stderr != Py_None) { PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW); } else { PyObject_Print(value, stderr, Py_PRINT_RAW); fflush(stderr); } PySys_WriteStderr("\n"); exitcode = 1; } done: /* Restore and clear the exception info, in order to properly decref * the exception, value, and traceback. If we just exit instead, * these leak, which confuses PYTHONDUMPREFS output, and may prevent * some finalizers from running. */ PyErr_Restore(exception, value, tb); PyErr_Clear(); Py_Exit(exitcode); /* NOTREACHED */ } void PyErr_PrintEx(int set_sys_last_vars) { PyObject *exception, *v, *tb, *hook; if (PyErr_ExceptionMatches(PyExc_SystemExit)) { handle_system_exit(); } PyErr_Fetch(&exception, &v, &tb); if (exception == NULL) return; PyErr_NormalizeException(&exception, &v, &tb); if (tb == NULL) { tb = Py_None; Py_INCREF(tb); } PyException_SetTraceback(v, tb); if (exception == NULL) return; /* Now we know v != NULL too */ if (set_sys_last_vars) { if (_PySys_SetObjectId(&PyId_last_type, exception) < 0) { PyErr_Clear(); } if (_PySys_SetObjectId(&PyId_last_value, v) < 0) { PyErr_Clear(); } if (_PySys_SetObjectId(&PyId_last_traceback, tb) < 0) { PyErr_Clear(); } } hook = _PySys_GetObjectId(&PyId_excepthook); if (hook) { PyObject* stack[3]; PyObject *result; stack[0] = exception; stack[1] = v; stack[2] = tb; result = _PyObject_FastCall(hook, stack, 3); if (result == NULL) { PyObject *exception2, *v2, *tb2; if (PyErr_ExceptionMatches(PyExc_SystemExit)) { handle_system_exit(); } PyErr_Fetch(&exception2, &v2, &tb2); PyErr_NormalizeException(&exception2, &v2, &tb2); /* It should not be possible for exception2 or v2 to be NULL. However PyErr_Display() can't tolerate NULLs, so just be safe. */ if (exception2 == NULL) { exception2 = Py_None; Py_INCREF(exception2); } if (v2 == NULL) { v2 = Py_None; Py_INCREF(v2); } fflush(stdout); PySys_WriteStderr("Error in sys.excepthook:\n"); PyErr_Display(exception2, v2, tb2); PySys_WriteStderr("\nOriginal exception was:\n"); PyErr_Display(exception, v, tb); Py_DECREF(exception2); Py_DECREF(v2); Py_XDECREF(tb2); } Py_XDECREF(result); } else { PySys_WriteStderr("sys.excepthook is missing\n"); PyErr_Display(exception, v, tb); } Py_XDECREF(exception); Py_XDECREF(v); Py_XDECREF(tb); } static void print_exception(PyObject *f, PyObject *value) { int err = 0; PyObject *type, *tb; _Py_IDENTIFIER(print_file_and_line); if (!PyExceptionInstance_Check(value)) { err = PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f); err += PyFile_WriteString(Py_TYPE(value)->tp_name, f); err += PyFile_WriteString(" found\n", f); if (err) PyErr_Clear(); return; } Py_INCREF(value); fflush(stdout); type = (PyObject *) Py_TYPE(value); tb = PyException_GetTraceback(value); if (tb && tb != Py_None) err = PyTraceBack_Print(tb, f); if (err == 0 && _PyObject_HasAttrId(value, &PyId_print_file_and_line)) { PyObject *message, *filename, *text; int lineno, offset; if (!parse_syntax_error(value, &message, &filename, &lineno, &offset, &text)) PyErr_Clear(); else { PyObject *line; Py_DECREF(value); value = message; line = PyUnicode_FromFormat(" File \"%U\", line %d\n", filename, lineno); Py_DECREF(filename); if (line != NULL) { PyFile_WriteObject(line, f, Py_PRINT_RAW); Py_DECREF(line); } if (text != NULL) { print_error_text(f, offset, text); Py_DECREF(text); } /* Can't be bothered to check all those PyFile_WriteString() calls */ if (PyErr_Occurred()) err = -1; } } if (err) { /* Don't do anything else */ } else { PyObject* moduleName; char* className; _Py_IDENTIFIER(__module__); assert(PyExceptionClass_Check(type)); className = PyExceptionClass_Name(type); if (className != NULL) { char *dot = strrchr(className, '.'); if (dot != NULL) className = dot+1; } moduleName = _PyObject_GetAttrId(type, &PyId___module__); if (moduleName == NULL || !PyUnicode_Check(moduleName)) { Py_XDECREF(moduleName); err = PyFile_WriteString("<unknown>", f); } else { if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) { err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW); err += PyFile_WriteString(".", f); } Py_DECREF(moduleName); } if (err == 0) { if (className == NULL) err = PyFile_WriteString("<unknown>", f); else err = PyFile_WriteString(className, f); } } if (err == 0 && (value != Py_None)) { PyObject *s = PyObject_Str(value); /* only print colon if the str() of the object is not the empty string */ if (s == NULL) { PyErr_Clear(); err = -1; PyFile_WriteString(": <exception str() failed>", f); } else if (!PyUnicode_Check(s) || PyUnicode_GetLength(s) != 0) err = PyFile_WriteString(": ", f); if (err == 0) err = PyFile_WriteObject(s, f, Py_PRINT_RAW); Py_XDECREF(s); } /* try to write a newline in any case */ if (err < 0) { PyErr_Clear(); } err += PyFile_WriteString("\n", f); Py_XDECREF(tb); Py_DECREF(value); /* If an error happened here, don't show it. XXX This is wrong, but too many callers rely on this behavior. */ if (err != 0) PyErr_Clear(); } static const char cause_message[] = "\nThe above exception was the direct cause " "of the following exception:\n\n"; static const char context_message[] = "\nDuring handling of the above exception, " "another exception occurred:\n\n"; static void print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen) { int err = 0, res; PyObject *cause, *context; if (seen != NULL) { /* Exception chaining */ PyObject *value_id = PyLong_FromVoidPtr(value); if (value_id == NULL || PySet_Add(seen, value_id) == -1) PyErr_Clear(); else if (PyExceptionInstance_Check(value)) { PyObject *check_id = NULL; cause = PyException_GetCause(value); context = PyException_GetContext(value); if (cause) { check_id = PyLong_FromVoidPtr(cause); if (check_id == NULL) { res = -1; } else { res = PySet_Contains(seen, check_id); Py_DECREF(check_id); } if (res == -1) PyErr_Clear(); if (res == 0) { print_exception_recursive( f, cause, seen); err |= PyFile_WriteString( cause_message, f); } } else if (context && !((PyBaseExceptionObject *)value)->suppress_context) { check_id = PyLong_FromVoidPtr(context); if (check_id == NULL) { res = -1; } else { res = PySet_Contains(seen, check_id); Py_DECREF(check_id); } if (res == -1) PyErr_Clear(); if (res == 0) { print_exception_recursive( f, context, seen); err |= PyFile_WriteString( context_message, f); } } Py_XDECREF(context); Py_XDECREF(cause); } Py_XDECREF(value_id); } print_exception(f, value); if (err != 0) PyErr_Clear(); } void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb) { PyObject *seen; PyObject *f = _PySys_GetObjectId(&PyId_stderr); if (PyExceptionInstance_Check(value) && tb != NULL && PyTraceBack_Check(tb)) { /* Put the traceback on the exception, otherwise it won't get displayed. See issue #18776. */ PyObject *cur_tb = PyException_GetTraceback(value); if (cur_tb == NULL) PyException_SetTraceback(value, tb); else Py_DECREF(cur_tb); } if (f == Py_None) { /* pass */ } else if (f == NULL) { _PyObject_Dump(value); fprintf(stderr, "lost sys.stderr\n"); } else { /* We choose to ignore seen being possibly NULL, and report at least the main exception (it could be a MemoryError). */ seen = PySet_New(NULL); if (seen == NULL) PyErr_Clear(); print_exception_recursive(f, value, seen); Py_XDECREF(seen); } } PyObject * PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { PyObject *ret = NULL; mod_ty mod; PyArena *arena; PyObject *filename; filename = _PyUnicode_FromId(&PyId_string); /* borrowed */ if (filename == NULL) return NULL; arena = PyArena_New(); if (arena == NULL) return NULL; mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena); if (mod != NULL) ret = run_mod(mod, filename, globals, locals, flags, arena); PyArena_Free(arena); return ret; } PyObject * PyRun_FileExFlags(FILE *fp, const char *filename_str, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags) { PyObject *ret = NULL; mod_ty mod; PyArena *arena = NULL; PyObject *filename; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) goto exit; arena = PyArena_New(); if (arena == NULL) goto exit; mod = PyParser_ASTFromFileObject(fp, filename, NULL, start, 0, 0, flags, NULL, arena); if (closeit) fclose(fp); if (mod == NULL) { goto exit; } ret = run_mod(mod, filename, globals, locals, flags, arena); exit: Py_XDECREF(filename); if (arena != NULL) PyArena_Free(arena); return ret; } static void flush_io(void) { PyObject *f, *r; PyObject *type, *value, *traceback; /* Save the current exception */ PyErr_Fetch(&type, &value, &traceback); f = _PySys_GetObjectId(&PyId_stderr); if (f != NULL) { r = _PyObject_CallMethodId(f, &PyId_flush, NULL); if (r) Py_DECREF(r); else PyErr_Clear(); } f = _PySys_GetObjectId(&PyId_stdout); if (f != NULL) { r = _PyObject_CallMethodId(f, &PyId_flush, NULL); if (r) Py_DECREF(r); else PyErr_Clear(); } PyErr_Restore(type, value, traceback); } static PyObject * run_mod(mod_ty mod, PyObject *filename, PyObject *globals, PyObject *locals, PyCompilerFlags *flags, PyArena *arena) { PyCodeObject *co; PyObject *v; co = PyAST_CompileObject(mod, filename, flags, -1, arena); if (co == NULL) return NULL; v = PyEval_EvalCode((PyObject*)co, globals, locals); Py_DECREF(co); return v; } static PyObject * run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { PyCodeObject *co; PyObject *v; long magic; long PyImport_GetMagicNumber(void); magic = PyMarshal_ReadLongFromFile(fp); if (magic != PyImport_GetMagicNumber()) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError, "Bad magic number in .pyc file"); goto error; } /* Skip mtime and size */ (void) PyMarshal_ReadLongFromFile(fp); (void) PyMarshal_ReadLongFromFile(fp); if (PyErr_Occurred()) { goto error; } v = PyMarshal_ReadLastObjectFromFile(fp); if (v == NULL || !PyCode_Check(v)) { Py_XDECREF(v); PyErr_SetString(PyExc_RuntimeError, "Bad code object in .pyc file"); goto error; } fclose(fp); co = (PyCodeObject *)v; v = PyEval_EvalCode((PyObject*)co, globals, locals); if (v && flags) flags->cf_flags |= (co->co_flags & PyCF_MASK); Py_DECREF(co); return v; error: fclose(fp); return NULL; } PyObject * Py_CompileStringObject(const char *str, PyObject *filename, int start, PyCompilerFlags *flags, int optimize) { PyCodeObject *co; mod_ty mod; PyArena *arena = PyArena_New(); if (arena == NULL) return NULL; mod = PyParser_ASTFromStringObject(str, filename, start, flags, arena); if (mod == NULL) { PyArena_Free(arena); return NULL; } if (flags && (flags->cf_flags & PyCF_ONLY_AST)) { PyObject *result = PyAST_mod2obj(mod); PyArena_Free(arena); return result; } co = PyAST_CompileObject(mod, filename, flags, optimize, arena); PyArena_Free(arena); return (PyObject *)co; } PyObject * Py_CompileStringExFlags(const char *str, const char *filename_str, int start, PyCompilerFlags *flags, int optimize) { PyObject *filename, *co; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) return NULL; co = Py_CompileStringObject(str, filename, start, flags, optimize); Py_DECREF(filename); return co; } /* For use in Py_LIMITED_API */ #undef Py_CompileString PyObject * PyCompileString(const char *str, const char *filename, int start) { return Py_CompileStringFlags(str, filename, start, NULL); } struct symtable * Py_SymtableStringObject(const char *str, PyObject *filename, int start) { struct symtable *st; mod_ty mod; PyCompilerFlags flags; PyArena *arena; arena = PyArena_New(); if (arena == NULL) return NULL; flags.cf_flags = 0; mod = PyParser_ASTFromStringObject(str, filename, start, &flags, arena); if (mod == NULL) { PyArena_Free(arena); return NULL; } st = PySymtable_BuildObject(mod, filename, 0); PyArena_Free(arena); return st; } struct symtable * Py_SymtableString(const char *str, const char *filename_str, int start) { PyObject *filename; struct symtable *st; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) return NULL; st = Py_SymtableStringObject(str, filename, start); Py_DECREF(filename); return st; } /* Preferred access to parser is through AST. */ mod_ty PyParser_ASTFromStringObject(const char *s, PyObject *filename, int start, PyCompilerFlags *flags, PyArena *arena) { mod_ty mod; PyCompilerFlags localflags; perrdetail err; int iflags = PARSER_FLAGS(flags); node *n = PyParser_ParseStringObject(s, filename, &_PyParser_Grammar, start, &err, &iflags); if (flags == NULL) { localflags.cf_flags = 0; flags = &localflags; } if (n) { flags->cf_flags |= iflags & PyCF_MASK; mod = PyAST_FromNodeObject(n, flags, filename, arena); PyNode_Free(n); } else { err_input(&err); mod = NULL; } err_free(&err); return mod; } mod_ty PyParser_ASTFromString(const char *s, const char *filename_str, int start, PyCompilerFlags *flags, PyArena *arena) { PyObject *filename; mod_ty mod; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) return NULL; mod = PyParser_ASTFromStringObject(s, filename, start, flags, arena); Py_DECREF(filename); return mod; } mod_ty PyParser_ASTFromFileObject(FILE *fp, PyObject *filename, const char* enc, int start, const char *ps1, const char *ps2, PyCompilerFlags *flags, int *errcode, PyArena *arena) { mod_ty mod; PyCompilerFlags localflags; perrdetail err; int iflags = PARSER_FLAGS(flags); node *n = PyParser_ParseFileObject(fp, filename, enc, &_PyParser_Grammar, start, ps1, ps2, &err, &iflags); if (flags == NULL) { localflags.cf_flags = 0; flags = &localflags; } if (n) { flags->cf_flags |= iflags & PyCF_MASK; mod = PyAST_FromNodeObject(n, flags, filename, arena); PyNode_Free(n); } else { err_input(&err); if (errcode) *errcode = err.error; mod = NULL; } err_free(&err); return mod; } mod_ty PyParser_ASTFromFile(FILE *fp, const char *filename_str, const char* enc, int start, const char *ps1, const char *ps2, PyCompilerFlags *flags, int *errcode, PyArena *arena) { mod_ty mod; PyObject *filename; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) return NULL; mod = PyParser_ASTFromFileObject(fp, filename, enc, start, ps1, ps2, flags, errcode, arena); Py_DECREF(filename); return mod; } /* Simplified interface to parsefile -- return node or set exception */ node * PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) { perrdetail err; node *n = PyParser_ParseFileFlags(fp, filename, NULL, &_PyParser_Grammar, start, NULL, NULL, &err, flags); if (n == NULL) err_input(&err); err_free(&err); return n; } /* Simplified interface to parsestring -- return node or set exception */ node * PyParser_SimpleParseStringFlags(const char *str, int start, int flags) { perrdetail err; node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar, start, &err, flags); if (n == NULL) err_input(&err); err_free(&err); return n; } node * PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename, int start, int flags) { perrdetail err; node *n = PyParser_ParseStringFlagsFilename(str, filename, &_PyParser_Grammar, start, &err, flags); if (n == NULL) err_input(&err); err_free(&err); return n; } node * PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start) { return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0); } /* May want to move a more generalized form of this to parsetok.c or even parser modules. */ void PyParser_ClearError(perrdetail *err) { err_free(err); } void PyParser_SetError(perrdetail *err) { err_input(err); } static void err_free(perrdetail *err) { Py_CLEAR(err->filename); } /* Set the error appropriate to the given input error code (see errcode.h) */ static void err_input(perrdetail *err) { PyObject *v, *w, *errtype, *errtext; PyObject *msg_obj = NULL; char *msg = NULL; int offset = err->offset; errtype = PyExc_SyntaxError; switch (err->error) { case E_ERROR: goto cleanup; case E_SYNTAX: errtype = PyExc_IndentationError; if (err->expected == INDENT) msg = "expected an indented block"; else if (err->token == INDENT) msg = "unexpected indent"; else if (err->token == DEDENT) msg = "unexpected unindent"; else if (err->expected == NOTEQUAL) { errtype = PyExc_SyntaxError; msg = "with Barry as BDFL, use '<>' instead of '!='"; } else { errtype = PyExc_SyntaxError; msg = "invalid syntax"; } break; case E_TOKEN: msg = "invalid token"; break; case E_EOFS: msg = "EOF while scanning triple-quoted string literal"; break; case E_EOLS: msg = "EOL while scanning string literal"; break; case E_INTR: if (!PyErr_Occurred()) PyErr_SetNone(PyExc_KeyboardInterrupt); goto cleanup; case E_NOMEM: PyErr_NoMemory(); goto cleanup; case E_EOF: msg = "unexpected EOF while parsing"; break; case E_TABSPACE: errtype = PyExc_TabError; msg = "inconsistent use of tabs and spaces in indentation"; break; case E_OVERFLOW: msg = "expression too long"; break; case E_DEDENT: errtype = PyExc_IndentationError; msg = "unindent does not match any outer indentation level"; break; case E_TOODEEP: errtype = PyExc_IndentationError; msg = "too many levels of indentation"; break; case E_DECODE: { PyObject *type, *value, *tb; PyErr_Fetch(&type, &value, &tb); msg = "unknown decode error"; if (value != NULL) msg_obj = PyObject_Str(value); Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(tb); break; } case E_LINECONT: msg = "unexpected character after line continuation character"; break; case E_IDENTIFIER: msg = "invalid character in identifier"; break; case E_BADSINGLE: msg = "multiple statements found while compiling a single statement"; break; default: fprintf(stderr, "error=%d\n", err->error); msg = "unknown parsing error"; break; } /* err->text may not be UTF-8 in case of decoding errors. Explicitly convert to an object. */ if (!err->text) { errtext = Py_None; Py_INCREF(Py_None); } else { errtext = PyUnicode_DecodeUTF8(err->text, err->offset, "replace"); if (errtext != NULL) { Py_ssize_t len = strlen(err->text); offset = (int)PyUnicode_GET_LENGTH(errtext); if (len != err->offset) { Py_DECREF(errtext); errtext = PyUnicode_DecodeUTF8(err->text, len, "replace"); } } } v = Py_BuildValue("(OiiN)", err->filename, err->lineno, offset, errtext); if (v != NULL) { if (msg_obj) w = Py_BuildValue("(OO)", msg_obj, v); else w = Py_BuildValue("(sO)", msg, v); } else w = NULL; Py_XDECREF(v); PyErr_SetObject(errtype, w); Py_XDECREF(w); cleanup: Py_XDECREF(msg_obj); if (err->text != NULL) { PyObject_FREE(err->text); err->text = NULL; } } #if defined(USE_STACKCHECK) #if defined(WIN32) && defined(_MSC_VER) /* Stack checking for Microsoft C */ /* * Return non-zero when we run out of memory on the stack; zero otherwise. */ int PyOS_CheckStack(void) { __try { /* alloca throws a stack overflow exception if there's not enough space left on the stack */ alloca(PYOS_STACK_MARGIN * sizeof(void*)); return 0; } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { int errcode = _resetstkoflw(); if (errcode == 0) { Py_FatalError("Could not reset the stack!"); } } return 1; } #endif /* WIN32 && _MSC_VER */ /* Alternate implementations can be added here... */ #endif /* USE_STACKCHECK */ /* Deprecated C API functions still provided for binary compatibility */ #undef PyParser_SimpleParseFile node * PyParser_SimpleParseFile(FILE *fp, const char *filename, int start) { return PyParser_SimpleParseFileFlags(fp, filename, start, 0); } #undef PyParser_SimpleParseString node * PyParser_SimpleParseString(const char *str, int start) { return PyParser_SimpleParseStringFlags(str, start, 0); } #undef PyRun_AnyFile int PyRun_AnyFile(FILE *fp, const char *name) { return PyRun_AnyFileExFlags(fp, name, 0, NULL); } #undef PyRun_AnyFileEx int PyRun_AnyFileEx(FILE *fp, const char *name, int closeit) { return PyRun_AnyFileExFlags(fp, name, closeit, NULL); } #undef PyRun_AnyFileFlags int PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags) { return PyRun_AnyFileExFlags(fp, name, 0, flags); } #undef PyRun_File PyObject * PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l) { return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL); } #undef PyRun_FileEx PyObject * PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c) { return PyRun_FileExFlags(fp, p, s, g, l, c, NULL); } #undef PyRun_FileFlags PyObject * PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, PyCompilerFlags *flags) { return PyRun_FileExFlags(fp, p, s, g, l, 0, flags); } #undef PyRun_SimpleFile int PyRun_SimpleFile(FILE *f, const char *p) { return PyRun_SimpleFileExFlags(f, p, 0, NULL); } #undef PyRun_SimpleFileEx int PyRun_SimpleFileEx(FILE *f, const char *p, int c) { return PyRun_SimpleFileExFlags(f, p, c, NULL); } #undef PyRun_String PyObject * PyRun_String(const char *str, int s, PyObject *g, PyObject *l) { return PyRun_StringFlags(str, s, g, l, NULL); } #undef PyRun_SimpleString int PyRun_SimpleString(const char *s) { return PyRun_SimpleStringFlags(s, NULL); } #undef Py_CompileString PyObject * Py_CompileString(const char *str, const char *p, int s) { return Py_CompileStringExFlags(str, p, s, NULL, -1); } #undef Py_CompileStringFlags PyObject * Py_CompileStringFlags(const char *str, const char *p, int s, PyCompilerFlags *flags) { return Py_CompileStringExFlags(str, p, s, flags, -1); } #undef PyRun_InteractiveOne int PyRun_InteractiveOne(FILE *f, const char *p) { return PyRun_InteractiveOneFlags(f, p, NULL); } #undef PyRun_InteractiveLoop int PyRun_InteractiveLoop(FILE *f, const char *p) { return PyRun_InteractiveLoopFlags(f, p, NULL); }
45,785
1,599
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/dynload_dl.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Python/importdl.h" /* clang-format off */ /* Support for dynamic loading of extension modules */ extern char *Py_GetProgramName(void); const char *_PyImport_DynLoadFiletab[] = {".o", NULL}; dl_funcptr _PyImport_FindSharedFuncptr(const char *prefix, const char *shortname, const char *pathname, FILE *fp) { char funcname[258]; PyOS_snprintf(funcname, sizeof(funcname), "%.20s_%.200s", prefix, shortname); return dl_loadmod(Py_GetProgramName(), pathname, funcname); }
1,454
25
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/recursive.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/ceval.h" /* clang-format off */ int (Py_EnterRecursiveCall)(const char *where) { return Py_EnterRecursiveCall(where); } void (Py_LeaveRecursiveCall)(void) { Py_LeaveRecursiveCall(); }
2,067
33
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/dynload_stub.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Python/importdl.h" /* clang-format off */ /* This module provides the necessary stubs for when dynamic loading is not present. */ const char *_PyImport_DynLoadFiletab[] = {NULL};
1,029
14
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/frozenmodules.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2021 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/import.h" static const struct _frozen _PyImport_FrozenModules_Empty[1]; const struct _frozen *PyImport_FrozenModules = _PyImport_FrozenModules_Empty;
2,024
23
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/makeopcodetargets.py
#! /usr/bin/env python """Generate C code for the jump table of the threaded code interpreter (for compilers supporting computed gotos or "labels-as-values", such as gcc). """ import os import sys try: from importlib.machinery import SourceFileLoader except ImportError: import imp def find_module(modname): """Finds and returns a module in the local dist/checkout. """ modpath = os.path.join( os.path.dirname(os.path.dirname(__file__)), "Lib") return imp.load_module(modname, *imp.find_module(modname, [modpath])) else: def find_module(modname): """Finds and returns a module in the local dist/checkout. """ modpath = os.path.join( os.path.dirname(os.path.dirname(__file__)), "Lib", modname + ".py") return SourceFileLoader(modname, modpath).load_module() def write_contents(f): """Write C code contents to the target file object. """ opcode = find_module('opcode') targets = ['_unknown_opcode'] * 256 for opname, op in opcode.opmap.items(): targets[op] = "TARGET_%s" % opname f.write("static void *opcode_targets[256] = {\n") f.write(",\n".join([" &&%s" % s for s in targets])) f.write("\n};\n") def main(): if len(sys.argv) >= 3: sys.exit("Too many arguments") if len(sys.argv) == 2: target = sys.argv[1] else: target = "third_party/python/Python/opcode_targets.inc" with open(target, "w") as f: write_contents(f) print("Jump table written into %s" % target) if __name__ == "__main__": main()
1,609
56
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/frozen.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/import.h" /* clang-format off */ #include "o//third_party/python/Python/importlib.inc" #include "o//third_party/python/Python/importlib_external.inc" /* Dummy frozen modules initializer */ /* In order to test the support for frozen modules, by default we define a single frozen module, __hello__. Loading it will print some famous words... */ /* To regenerate this data after the bytecode or marshal format has changed, go to ../Tools/freeze/ and freeze the flag.py file; then copy and paste the appropriate bytes from M___main__.c. */ static unsigned char M___hello__[] = { 227,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0, 0,64,0,0,0,115,16,0,0,0,100,0,90,0,101,1, 100,1,131,1,1,0,100,2,83,0,41,3,84,122,12,72, 101,108,108,111,32,119,111,114,108,100,33,78,41,2,218,11, 105,110,105,116,105,97,108,105,122,101,100,218,5,112,114,105, 110,116,169,0,114,3,0,0,0,114,3,0,0,0,250,22, 46,47,84,111,111,108,115,47,102,114,101,101,122,101,47,102, 108,97,103,46,112,121,218,8,60,109,111,100,117,108,101,62, 1,0,0,0,115,2,0,0,0,4,1, }; #define SIZE (int)sizeof(M___hello__) const struct _frozen _PyImport_FrozenModules[] = { /* importlib */ {"_frozen_importlib", _Py_M__importlib, (int)sizeof(_Py_M__importlib)}, {"_frozen_importlib_external", _Py_M__importlib_external, (int)sizeof(_Py_M__importlib_external)}, /* Test module */ {"__hello__", M___hello__, SIZE}, /* Test package (negative size indicates package-ness) */ {"__phello__", M___hello__, -SIZE}, {"__phello__.spam", M___hello__, SIZE}, {0, 0, 0} /* sentinel */ };
2,454
49
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/formatter_unicode.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/str/locale.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pyport.h" #include "third_party/python/Include/pystrtod.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ /* implements the unicode (as opposed to string) version of the built-in formatters for string, int, float. that is, the versions of int.__float__, etc., that take and return unicode objects */ /* Raises an exception about an unknown presentation type for this * type. */ static void unknown_presentation_type(Py_UCS4 presentation_type, const char* type_name) { /* %c might be out-of-range, hence the two cases. */ if (presentation_type > 32 && presentation_type < 128) PyErr_Format(PyExc_ValueError, "Unknown format code '%c' " "for object of type '%.200s'", (char)presentation_type, type_name); else PyErr_Format(PyExc_ValueError, "Unknown format code '\\x%x' " "for object of type '%.200s'", (unsigned int)presentation_type, type_name); } static void invalid_thousands_separator_type(char specifier, Py_UCS4 presentation_type) { assert(specifier == ',' || specifier == '_'); if (presentation_type > 32 && presentation_type < 128) PyErr_Format(PyExc_ValueError, "Cannot specify '%c' with '%c'.", specifier, (char)presentation_type); else PyErr_Format(PyExc_ValueError, "Cannot specify '%c' with '\\x%x'.", specifier, (unsigned int)presentation_type); } static void invalid_comma_and_underscore(void) { PyErr_Format(PyExc_ValueError, "Cannot specify both ',' and '_'."); } /* get_integer consumes 0 or more decimal digit characters from an input string, updates *result with the corresponding positive integer, and returns the number of digits consumed. returns -1 on error. */ static int get_integer(PyObject *str, Py_ssize_t *ppos, Py_ssize_t end, Py_ssize_t *result) { Py_ssize_t accumulator, digitval, pos = *ppos; int numdigits; int kind = PyUnicode_KIND(str); void *data = PyUnicode_DATA(str); accumulator = numdigits = 0; for (; pos < end; pos++, numdigits++) { digitval = Py_UNICODE_TODECIMAL(PyUnicode_READ(kind, data, pos)); if (digitval < 0) break; /* 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"); *ppos = pos; return -1; } accumulator = accumulator * 10 + digitval; } *ppos = pos; *result = accumulator; return numdigits; } /************************************************************************/ /*********** standard format specifier parsing **************************/ /************************************************************************/ /* returns true if this character is a specifier alignment token */ Py_LOCAL_INLINE(int) is_alignment_token(Py_UCS4 c) { switch (c) { case '<': case '>': case '=': case '^': return 1; default: return 0; } } /* returns true if this character is a sign element */ Py_LOCAL_INLINE(int) is_sign_element(Py_UCS4 c) { switch (c) { case ' ': case '+': case '-': return 1; default: return 0; } } /* Locale type codes. LT_NO_LOCALE must be zero. */ enum LocaleType { LT_NO_LOCALE = 0, LT_DEFAULT_LOCALE = ',', LT_UNDERSCORE_LOCALE = '_', LT_UNDER_FOUR_LOCALE, LT_CURRENT_LOCALE }; typedef struct { Py_UCS4 fill_char; Py_UCS4 align; int alternate; Py_UCS4 sign; Py_ssize_t width; enum LocaleType thousands_separators; Py_ssize_t precision; Py_UCS4 type; } InternalFormatSpec; #if 0 /* Occasionally useful for debugging. Should normally be commented out. */ static void DEBUG_PRINT_FORMAT_SPEC(InternalFormatSpec *format) { printf("internal format spec: fill_char %d\n", format->fill_char); printf("internal format spec: align %d\n", format->align); printf("internal format spec: alternate %d\n", format->alternate); printf("internal format spec: sign %d\n", format->sign); printf("internal format spec: width %zd\n", format->width); printf("internal format spec: thousands_separators %d\n", format->thousands_separators); printf("internal format spec: precision %zd\n", format->precision); printf("internal format spec: type %c\n", format->type); printf("\n"); } #endif /* ptr points to the start of the format_spec, end points just past its end. fills in format with the parsed information. returns 1 on success, 0 on failure. if failure, sets the exception */ static int parse_internal_render_format_spec(PyObject *format_spec, Py_ssize_t start, Py_ssize_t end, InternalFormatSpec *format, char default_type, char default_align) { Py_ssize_t pos = start; int kind = PyUnicode_KIND(format_spec); void *data = PyUnicode_DATA(format_spec); /* end-pos is used throughout this code to specify the length of the input string */ #define READ_spec(index) PyUnicode_READ(kind, data, index) Py_ssize_t consumed; int align_specified = 0; int fill_char_specified = 0; format->fill_char = ' '; format->align = default_align; format->alternate = 0; format->sign = '\0'; format->width = -1; format->thousands_separators = LT_NO_LOCALE; format->precision = -1; format->type = default_type; /* If the second char is an alignment token, then parse the fill char */ if (end-pos >= 2 && is_alignment_token(READ_spec(pos+1))) { format->align = READ_spec(pos+1); format->fill_char = READ_spec(pos); fill_char_specified = 1; align_specified = 1; pos += 2; } else if (end-pos >= 1 && is_alignment_token(READ_spec(pos))) { format->align = READ_spec(pos); align_specified = 1; ++pos; } /* Parse the various sign options */ if (end-pos >= 1 && is_sign_element(READ_spec(pos))) { format->sign = READ_spec(pos); ++pos; } /* If the next character is #, we're in alternate mode. This only applies to integers. */ if (end-pos >= 1 && READ_spec(pos) == '#') { format->alternate = 1; ++pos; } /* The special case for 0-padding (backwards compat) */ if (!fill_char_specified && end-pos >= 1 && READ_spec(pos) == '0') { format->fill_char = '0'; if (!align_specified) { format->align = '='; } ++pos; } consumed = get_integer(format_spec, &pos, end, &format->width); if (consumed == -1) /* Overflow error. Exception already set. */ return 0; /* If consumed is 0, we didn't consume any characters for the width. In that case, reset the width to -1, because get_integer() will have set it to zero. -1 is how we record that the width wasn't specified. */ if (consumed == 0) format->width = -1; /* Comma signifies add thousands separators */ if (end-pos && READ_spec(pos) == ',') { format->thousands_separators = LT_DEFAULT_LOCALE; ++pos; } /* Underscore signifies add thousands separators */ if (end-pos && READ_spec(pos) == '_') { if (format->thousands_separators != LT_NO_LOCALE) { invalid_comma_and_underscore(); return 0; } format->thousands_separators = LT_UNDERSCORE_LOCALE; ++pos; } if (end-pos && READ_spec(pos) == ',') { invalid_comma_and_underscore(); return 0; } /* Parse field precision */ if (end-pos && READ_spec(pos) == '.') { ++pos; consumed = get_integer(format_spec, &pos, end, &format->precision); if (consumed == -1) /* Overflow error. Exception already set. */ return 0; /* Not having a precision after a dot is an error. */ if (consumed == 0) { PyErr_Format(PyExc_ValueError, "Format specifier missing precision"); return 0; } } /* Finally, parse the type field. */ if (end-pos > 1) { /* More than one char remain, invalid format specifier. */ PyErr_Format(PyExc_ValueError, "Invalid format specifier"); return 0; } if (end-pos == 1) { format->type = READ_spec(pos); ++pos; } /* Do as much validating as we can, just by looking at the format specifier. Do not take into account what type of formatting we're doing (int, float, string). */ if (format->thousands_separators) { switch (format->type) { case 'd': case 'e': case 'f': case 'g': case 'E': case 'G': case '%': case 'F': case '\0': /* These are allowed. See PEP 378.*/ break; case 'b': case 'o': case 'x': case 'X': /* Underscores are allowed in bin/oct/hex. See PEP 515. */ if (format->thousands_separators == LT_UNDERSCORE_LOCALE) { /* Every four digits, not every three, in bin/oct/hex. */ format->thousands_separators = LT_UNDER_FOUR_LOCALE; break; } /* fall through */ default: invalid_thousands_separator_type(format->thousands_separators, format->type); return 0; } } assert (format->align <= 127); assert (format->sign <= 127); return 1; } /* Calculate the padding needed. */ static void calc_padding(Py_ssize_t nchars, Py_ssize_t width, Py_UCS4 align, Py_ssize_t *n_lpadding, Py_ssize_t *n_rpadding, Py_ssize_t *n_total) { if (width >= 0) { if (nchars > width) *n_total = nchars; else *n_total = width; } else { /* not specified, use all of the chars and no more */ *n_total = nchars; } /* Figure out how much leading space we need, based on the aligning */ if (align == '>') *n_lpadding = *n_total - nchars; else if (align == '^') *n_lpadding = (*n_total - nchars) / 2; else if (align == '<' || align == '=') *n_lpadding = 0; else { /* We should never have an unspecified alignment. */ *n_lpadding = 0; assert(0); } *n_rpadding = *n_total - nchars - *n_lpadding; } /* Do the padding, and return a pointer to where the caller-supplied content goes. */ static int fill_padding(_PyUnicodeWriter *writer, Py_ssize_t nchars, Py_UCS4 fill_char, Py_ssize_t n_lpadding, Py_ssize_t n_rpadding) { Py_ssize_t pos; /* Pad on left. */ if (n_lpadding) { pos = writer->pos; _PyUnicode_FastFill(writer->buffer, pos, n_lpadding, fill_char); } /* Pad on right. */ if (n_rpadding) { pos = writer->pos + nchars + n_lpadding; _PyUnicode_FastFill(writer->buffer, pos, n_rpadding, fill_char); } /* Pointer to the user content. */ writer->pos += n_lpadding; return 0; } /************************************************************************/ /*********** common routines for numeric formatting *********************/ /************************************************************************/ /* Locale info needed for formatting integers and the part of floats before and including the decimal. Note that locales only support 8-bit chars, not unicode. */ typedef struct { PyObject *decimal_point; PyObject *thousands_sep; const char *grouping; char *grouping_buffer; } LocaleInfo; #define STATIC_LOCALE_INFO_INIT {0, 0, 0, 0} /* describes the layout for an integer, see the comment in calc_number_widths() for details */ typedef struct { Py_ssize_t n_lpadding; Py_ssize_t n_prefix; Py_ssize_t n_spadding; Py_ssize_t n_rpadding; char sign; Py_ssize_t n_sign; /* number of digits needed for sign (0/1) */ Py_ssize_t n_grouped_digits; /* Space taken up by the digits, including any grouping chars. */ Py_ssize_t n_decimal; /* 0 if only an integer */ Py_ssize_t n_remainder; /* Digits in decimal and/or exponent part, excluding the decimal itself, if present. */ /* These 2 are not the widths of fields, but are needed by STRINGLIB_GROUPING. */ Py_ssize_t n_digits; /* The number of digits before a decimal or exponent. */ Py_ssize_t n_min_width; /* The min_width we used when we computed the n_grouped_digits width. */ } NumberFieldWidths; /* Given a number of the form: digits[remainder] where ptr points to the start and end points to the end, find where the integer part ends. This could be a decimal, an exponent, both, or neither. If a decimal point is present, set *has_decimal and increment remainder beyond it. Results are undefined (but shouldn't crash) for improperly formatted strings. */ static void parse_number(PyObject *s, Py_ssize_t pos, Py_ssize_t end, Py_ssize_t *n_remainder, int *has_decimal) { Py_ssize_t remainder; int kind = PyUnicode_KIND(s); void *data = PyUnicode_DATA(s); while (pos<end && Py_ISDIGIT(PyUnicode_READ(kind, data, pos))) ++pos; remainder = pos; /* Does remainder start with a decimal point? */ *has_decimal = pos<end && PyUnicode_READ(kind, data, remainder) == '.'; /* Skip the decimal point. */ if (*has_decimal) remainder++; *n_remainder = end - remainder; } /* not all fields of format are used. for example, precision is unused. should this take discrete params in order to be more clear about what it does? or is passing a single format parameter easier and more efficient enough to justify a little obfuscation? Return -1 on error. */ static Py_ssize_t calc_number_widths(NumberFieldWidths *spec, Py_ssize_t n_prefix, Py_UCS4 sign_char, PyObject *number, Py_ssize_t n_start, Py_ssize_t n_end, Py_ssize_t n_remainder, int has_decimal, const LocaleInfo *locale, const InternalFormatSpec *format, Py_UCS4 *maxchar) { Py_ssize_t n_non_digit_non_padding; Py_ssize_t n_padding; spec->n_digits = n_end - n_start - n_remainder - (has_decimal?1:0); spec->n_lpadding = 0; spec->n_prefix = n_prefix; spec->n_decimal = has_decimal ? PyUnicode_GET_LENGTH(locale->decimal_point) : 0; spec->n_remainder = n_remainder; spec->n_spadding = 0; spec->n_rpadding = 0; spec->sign = '\0'; spec->n_sign = 0; /* the output will look like: | | | <lpadding> <sign> <prefix> <spadding> <grouped_digits> <decimal> <remainder> <rpadding> | | | sign is computed from format->sign and the actual sign of the number prefix is given (it's for the '0x' prefix) digits is already known the total width is either given, or computed from the actual digits only one of lpadding, spadding, and rpadding can be non-zero, and it's calculated from the width and other fields */ /* compute the various parts we're going to write */ switch (format->sign) { case '+': /* always put a + or - */ spec->n_sign = 1; spec->sign = (sign_char == '-' ? '-' : '+'); break; case ' ': spec->n_sign = 1; spec->sign = (sign_char == '-' ? '-' : ' '); break; default: /* Not specified, or the default (-) */ if (sign_char == '-') { spec->n_sign = 1; spec->sign = '-'; } } /* The number of chars used for non-digits and non-padding. */ n_non_digit_non_padding = spec->n_sign + spec->n_prefix + spec->n_decimal + spec->n_remainder; /* min_width can go negative, that's okay. format->width == -1 means we don't care. */ if (format->fill_char == '0' && format->align == '=') spec->n_min_width = format->width - n_non_digit_non_padding; else spec->n_min_width = 0; if (spec->n_digits == 0) /* This case only occurs when using 'c' formatting, we need to special case it because the grouping code always wants to have at least one character. */ spec->n_grouped_digits = 0; else { Py_UCS4 grouping_maxchar; spec->n_grouped_digits = _PyUnicode_InsertThousandsGrouping( NULL, 0, NULL, 0, spec->n_digits, spec->n_min_width, locale->grouping, locale->thousands_sep, &grouping_maxchar); if (spec->n_grouped_digits == -1) { return -1; } *maxchar = Py_MAX(*maxchar, grouping_maxchar); } /* Given the desired width and the total of digit and non-digit space we consume, see if we need any padding. format->width can be negative (meaning no padding), but this code still works in that case. */ n_padding = format->width - (n_non_digit_non_padding + spec->n_grouped_digits); if (n_padding > 0) { /* Some padding is needed. Determine if it's left, space, or right. */ switch (format->align) { case '<': spec->n_rpadding = n_padding; break; case '^': spec->n_lpadding = n_padding / 2; spec->n_rpadding = n_padding - spec->n_lpadding; break; case '=': spec->n_spadding = n_padding; break; case '>': spec->n_lpadding = n_padding; break; default: /* Shouldn't get here, but treat it as '>' */ spec->n_lpadding = n_padding; assert(0); break; } } if (spec->n_lpadding || spec->n_spadding || spec->n_rpadding) *maxchar = Py_MAX(*maxchar, format->fill_char); if (spec->n_decimal) *maxchar = Py_MAX(*maxchar, PyUnicode_MAX_CHAR_VALUE(locale->decimal_point)); return spec->n_lpadding + spec->n_sign + spec->n_prefix + spec->n_spadding + spec->n_grouped_digits + spec->n_decimal + spec->n_remainder + spec->n_rpadding; } /* Fill in the digit parts of a numbers's string representation, as determined in calc_number_widths(). Return -1 on error, or 0 on success. */ static int fill_number(_PyUnicodeWriter *writer, const NumberFieldWidths *spec, PyObject *digits, Py_ssize_t d_start, Py_ssize_t d_end, PyObject *prefix, Py_ssize_t p_start, Py_UCS4 fill_char, LocaleInfo *locale, int toupper) { /* Used to keep track of digits, decimal, and remainder. */ Py_ssize_t d_pos = d_start; const unsigned int kind = writer->kind; const void *data = writer->data; Py_ssize_t r; if (spec->n_lpadding) { _PyUnicode_FastFill(writer->buffer, writer->pos, spec->n_lpadding, fill_char); writer->pos += spec->n_lpadding; } if (spec->n_sign == 1) { PyUnicode_WRITE(kind, data, writer->pos, spec->sign); writer->pos++; } if (spec->n_prefix) { _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos, prefix, p_start, spec->n_prefix); if (toupper) { Py_ssize_t t; for (t = 0; t < spec->n_prefix; t++) { Py_UCS4 c = PyUnicode_READ(kind, data, writer->pos + t); c = Py_TOUPPER(c); assert (c <= 127); PyUnicode_WRITE(kind, data, writer->pos + t, c); } } writer->pos += spec->n_prefix; } if (spec->n_spadding) { _PyUnicode_FastFill(writer->buffer, writer->pos, spec->n_spadding, fill_char); writer->pos += spec->n_spadding; } /* Only for type 'c' special case, it has no digits. */ if (spec->n_digits != 0) { /* Fill the digits with InsertThousandsGrouping. */ r = _PyUnicode_InsertThousandsGrouping( writer, spec->n_grouped_digits, digits, d_pos, spec->n_digits, spec->n_min_width, locale->grouping, locale->thousands_sep, NULL); if (r == -1) return -1; assert(r == spec->n_grouped_digits); d_pos += spec->n_digits; } if (toupper) { Py_ssize_t t; for (t = 0; t < spec->n_grouped_digits; t++) { Py_UCS4 c = PyUnicode_READ(kind, data, writer->pos + t); c = Py_TOUPPER(c); if (c > 127) { PyErr_SetString(PyExc_SystemError, "non-ascii grouped digit"); return -1; } PyUnicode_WRITE(kind, data, writer->pos + t, c); } } writer->pos += spec->n_grouped_digits; if (spec->n_decimal) { _PyUnicode_FastCopyCharacters( writer->buffer, writer->pos, locale->decimal_point, 0, spec->n_decimal); writer->pos += spec->n_decimal; d_pos += 1; } if (spec->n_remainder) { _PyUnicode_FastCopyCharacters( writer->buffer, writer->pos, digits, d_pos, spec->n_remainder); writer->pos += spec->n_remainder; /* d_pos += spec->n_remainder; */ } if (spec->n_rpadding) { _PyUnicode_FastFill(writer->buffer, writer->pos, spec->n_rpadding, fill_char); writer->pos += spec->n_rpadding; } return 0; } static const char no_grouping[1] = {CHAR_MAX}; /* Find the decimal point character(s?), thousands_separator(s?), and grouping description, either for the current locale if type is LT_CURRENT_LOCALE, a hard-coded locale if LT_DEFAULT_LOCALE or LT_UNDERSCORE_LOCALE/LT_UNDER_FOUR_LOCALE, or none if LT_NO_LOCALE. */ static int get_locale_info(enum LocaleType type, LocaleInfo *locale_info) { switch (type) { case LT_CURRENT_LOCALE: { const char *grouping; if (_Py_GetLocaleconvNumeric(&locale_info->decimal_point, &locale_info->thousands_sep, &grouping) < 0) { return -1; } /* localeconv() grouping can become a dangling pointer or point to a different string if another thread calls localeconv() during the string formatting. Copy the string to avoid this risk. */ locale_info->grouping_buffer = _PyMem_Strdup(grouping); if (locale_info->grouping_buffer == NULL) { PyErr_NoMemory(); return -1; } locale_info->grouping = locale_info->grouping_buffer; break; } case LT_DEFAULT_LOCALE: case LT_UNDERSCORE_LOCALE: case LT_UNDER_FOUR_LOCALE: locale_info->decimal_point = PyUnicode_FromOrdinal('.'); locale_info->thousands_sep = PyUnicode_FromOrdinal( type == LT_DEFAULT_LOCALE ? ',' : '_'); if (!locale_info->decimal_point || !locale_info->thousands_sep) return -1; if (type != LT_UNDER_FOUR_LOCALE) locale_info->grouping = "\3"; /* Group every 3 characters. The (implicit) trailing 0 means repeat infinitely. */ else locale_info->grouping = "\4"; /* Bin/oct/hex group every four. */ break; case LT_NO_LOCALE: locale_info->decimal_point = PyUnicode_FromOrdinal('.'); locale_info->thousands_sep = PyUnicode_New(0, 0); if (!locale_info->decimal_point || !locale_info->thousands_sep) return -1; locale_info->grouping = no_grouping; break; } return 0; } static void free_locale_info(LocaleInfo *locale_info) { Py_XDECREF(locale_info->decimal_point); Py_XDECREF(locale_info->thousands_sep); PyMem_Free(locale_info->grouping_buffer); } /************************************************************************/ /*********** string formatting ******************************************/ /************************************************************************/ static int format_string_internal(PyObject *value, const InternalFormatSpec *format, _PyUnicodeWriter *writer) { Py_ssize_t lpad; Py_ssize_t rpad; Py_ssize_t total; Py_ssize_t len; int result = -1; Py_UCS4 maxchar; assert(PyUnicode_IS_READY(value)); len = PyUnicode_GET_LENGTH(value); /* sign is not allowed on strings */ if (format->sign != '\0') { PyErr_SetString(PyExc_ValueError, "Sign not allowed in string format specifier"); goto done; } /* alternate is not allowed on strings */ if (format->alternate) { PyErr_SetString(PyExc_ValueError, "Alternate form (#) not allowed in string format " "specifier"); goto done; } /* '=' alignment not allowed on strings */ if (format->align == '=') { PyErr_SetString(PyExc_ValueError, "'=' alignment not allowed " "in string format specifier"); goto done; } if ((format->width == -1 || format->width <= len) && (format->precision == -1 || format->precision >= len)) { /* Fast path */ return _PyUnicodeWriter_WriteStr(writer, value); } /* if precision is specified, output no more that format.precision characters */ if (format->precision >= 0 && len >= format->precision) { len = format->precision; } calc_padding(len, format->width, format->align, &lpad, &rpad, &total); maxchar = writer->maxchar; if (lpad != 0 || rpad != 0) maxchar = Py_MAX(maxchar, format->fill_char); if (PyUnicode_MAX_CHAR_VALUE(value) > maxchar) { Py_UCS4 valmaxchar = _PyUnicode_FindMaxChar(value, 0, len); maxchar = Py_MAX(maxchar, valmaxchar); } /* allocate the resulting string */ if (_PyUnicodeWriter_Prepare(writer, total, maxchar) == -1) goto done; /* Write into that space. First the padding. */ result = fill_padding(writer, len, format->fill_char, lpad, rpad); if (result == -1) goto done; /* Then the source string. */ if (len) { _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos, value, 0, len); } writer->pos += (len + rpad); result = 0; done: return result; } /************************************************************************/ /*********** long formatting ********************************************/ /************************************************************************/ static int format_long_internal(PyObject *value, const InternalFormatSpec *format, _PyUnicodeWriter *writer) { int result = -1; Py_UCS4 maxchar = 127; PyObject *tmp = NULL; Py_ssize_t inumeric_chars; Py_UCS4 sign_char = '\0'; Py_ssize_t n_digits; /* count of digits need from the computed string */ Py_ssize_t n_remainder = 0; /* Used only for 'c' formatting, which produces non-digits */ Py_ssize_t n_prefix = 0; /* Count of prefix chars, (e.g., '0x') */ Py_ssize_t n_total; Py_ssize_t prefix = 0; NumberFieldWidths spec; long x; /* Locale settings, either from the actual locale or from a hard-code pseudo-locale */ LocaleInfo locale = STATIC_LOCALE_INFO_INIT; /* no precision allowed on integers */ if (format->precision != -1) { PyErr_SetString(PyExc_ValueError, "Precision not allowed in integer format specifier"); goto done; } /* special case for character formatting */ if (format->type == 'c') { /* error to specify a sign */ if (format->sign != '\0') { PyErr_SetString(PyExc_ValueError, "Sign not allowed with integer" " format specifier 'c'"); goto done; } /* error to request alternate format */ if (format->alternate) { PyErr_SetString(PyExc_ValueError, "Alternate form (#) not allowed with integer" " format specifier 'c'"); goto done; } /* taken from unicodeobject.c formatchar() */ /* Integer input truncated to a character */ x = PyLong_AsLong(value); if (x == -1 && PyErr_Occurred()) goto done; if (x < 0 || x > 0x10ffff) { PyErr_SetString(PyExc_OverflowError, "%c arg not in range(0x110000)"); goto done; } tmp = PyUnicode_FromOrdinal(x); inumeric_chars = 0; n_digits = 1; maxchar = Py_MAX(maxchar, (Py_UCS4)x); /* As a sort-of hack, we tell calc_number_widths that we only have "remainder" characters. calc_number_widths thinks these are characters that don't get formatted, only copied into the output string. We do this for 'c' formatting, because the characters are likely to be non-digits. */ n_remainder = 1; } else { int base; int leading_chars_to_skip = 0; /* Number of characters added by PyNumber_ToBase that we want to skip over. */ /* Compute the base and how many characters will be added by PyNumber_ToBase */ switch (format->type) { case 'b': base = 2; leading_chars_to_skip = 2; /* 0b */ break; case 'o': base = 8; leading_chars_to_skip = 2; /* 0o */ break; case 'x': case 'X': base = 16; leading_chars_to_skip = 2; /* 0x */ break; default: /* shouldn't be needed, but stops a compiler warning */ case 'd': case 'n': base = 10; break; } if (format->sign != '+' && format->sign != ' ' && format->width == -1 && format->type != 'X' && format->type != 'n' && !format->thousands_separators && PyLong_CheckExact(value)) { /* Fast path */ return _PyLong_FormatWriter(writer, value, base, format->alternate); } /* The number of prefix chars is the same as the leading chars to skip */ if (format->alternate) n_prefix = leading_chars_to_skip; /* Do the hard part, converting to a string in a given base */ tmp = _PyLong_Format(value, base); if (tmp == NULL || PyUnicode_READY(tmp) == -1) goto done; inumeric_chars = 0; n_digits = PyUnicode_GET_LENGTH(tmp); prefix = inumeric_chars; /* Is a sign character present in the output? If so, remember it and skip it */ if (PyUnicode_READ_CHAR(tmp, inumeric_chars) == '-') { sign_char = '-'; ++prefix; ++leading_chars_to_skip; } /* Skip over the leading chars (0x, 0b, etc.) */ n_digits -= leading_chars_to_skip; inumeric_chars += leading_chars_to_skip; } /* Determine the grouping, separator, and decimal point, if any. */ if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE : format->thousands_separators, &locale) == -1) goto done; /* Calculate how much memory we'll need. */ n_total = calc_number_widths(&spec, n_prefix, sign_char, tmp, inumeric_chars, inumeric_chars + n_digits, n_remainder, 0, &locale, format, &maxchar); if (n_total == -1) { goto done; } /* Allocate the memory. */ if (_PyUnicodeWriter_Prepare(writer, n_total, maxchar) == -1) goto done; /* Populate the memory. */ result = fill_number(writer, &spec, tmp, inumeric_chars, inumeric_chars + n_digits, tmp, prefix, format->fill_char, &locale, format->type == 'X'); done: Py_XDECREF(tmp); free_locale_info(&locale); return result; } /************************************************************************/ /*********** float formatting *******************************************/ /************************************************************************/ /* much of this is taken from unicodeobject.c */ static int format_float_internal(PyObject *value, const InternalFormatSpec *format, _PyUnicodeWriter *writer) { char *buf = NULL; /* buffer returned from PyOS_double_to_string */ Py_ssize_t n_digits; Py_ssize_t n_remainder; Py_ssize_t n_total; int has_decimal; double val; int precision, default_precision = 6; Py_UCS4 type = format->type; int add_pct = 0; Py_ssize_t index; NumberFieldWidths spec; int flags = 0; int result = -1; Py_UCS4 maxchar = 127; Py_UCS4 sign_char = '\0'; int float_type; /* Used to see if we have a nan, inf, or regular float. */ PyObject *unicode_tmp = NULL; /* Locale settings, either from the actual locale or from a hard-code pseudo-locale */ LocaleInfo locale = STATIC_LOCALE_INFO_INIT; if (format->precision > INT_MAX) { PyErr_SetString(PyExc_ValueError, "precision too big"); goto done; } precision = (int)format->precision; if (format->alternate) flags |= Py_DTSF_ALT; if (type == '\0') { /* Omitted type specifier. Behaves in the same way as repr(x) and str(x) if no precision is given, else like 'g', but with at least one digit after the decimal point. */ flags |= Py_DTSF_ADD_DOT_0; type = 'r'; default_precision = 0; } if (type == 'n') /* 'n' is the same as 'g', except for the locale used to format the result. We take care of that later. */ type = 'g'; val = PyFloat_AsDouble(value); if (val == -1.0 && PyErr_Occurred()) goto done; if (type == '%') { type = 'f'; val *= 100; add_pct = 1; } if (precision < 0) precision = default_precision; else if (type == 'r') type = 'g'; /* Cast "type", because if we're in unicode we need to pass an 8-bit char. This is safe, because we've restricted what "type" can be. */ buf = PyOS_double_to_string(val, (char)type, precision, flags, &float_type); if (buf == NULL) goto done; n_digits = strlen(buf); if (add_pct) { /* We know that buf has a trailing zero (since we just called strlen() on it), and we don't use that fact any more. So we can just write over the trailing zero. */ buf[n_digits] = '%'; n_digits += 1; } if (format->sign != '+' && format->sign != ' ' && format->width == -1 && format->type != 'n' && !format->thousands_separators) { /* Fast path */ result = _PyUnicodeWriter_WriteASCIIString(writer, buf, n_digits); PyMem_Free(buf); return result; } /* Since there is no unicode version of PyOS_double_to_string, just use the 8 bit version and then convert to unicode. */ unicode_tmp = _PyUnicode_FromASCII(buf, n_digits); PyMem_Free(buf); if (unicode_tmp == NULL) goto done; /* Is a sign character present in the output? If so, remember it and skip it */ index = 0; if (PyUnicode_READ_CHAR(unicode_tmp, index) == '-') { sign_char = '-'; ++index; --n_digits; } /* Determine if we have any "remainder" (after the digits, might include decimal or exponent or both (or neither)) */ parse_number(unicode_tmp, index, index + n_digits, &n_remainder, &has_decimal); /* Determine the grouping, separator, and decimal point, if any. */ if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE : format->thousands_separators, &locale) == -1) goto done; /* Calculate how much memory we'll need. */ n_total = calc_number_widths(&spec, 0, sign_char, unicode_tmp, index, index + n_digits, n_remainder, has_decimal, &locale, format, &maxchar); if (n_total == -1) { goto done; } /* Allocate the memory. */ if (_PyUnicodeWriter_Prepare(writer, n_total, maxchar) == -1) goto done; /* Populate the memory. */ result = fill_number(writer, &spec, unicode_tmp, index, index + n_digits, NULL, 0, format->fill_char, &locale, 0); done: Py_XDECREF(unicode_tmp); free_locale_info(&locale); return result; } /************************************************************************/ /*********** complex formatting *****************************************/ /************************************************************************/ static int format_complex_internal(PyObject *value, const InternalFormatSpec *format, _PyUnicodeWriter *writer) { double re; double im; char *re_buf = NULL; /* buffer returned from PyOS_double_to_string */ char *im_buf = NULL; /* buffer returned from PyOS_double_to_string */ InternalFormatSpec tmp_format = *format; Py_ssize_t n_re_digits; Py_ssize_t n_im_digits; Py_ssize_t n_re_remainder; Py_ssize_t n_im_remainder; Py_ssize_t n_re_total; Py_ssize_t n_im_total; int re_has_decimal; int im_has_decimal; int precision, default_precision = 6; Py_UCS4 type = format->type; Py_ssize_t i_re; Py_ssize_t i_im; NumberFieldWidths re_spec; NumberFieldWidths im_spec; int flags = 0; int result = -1; Py_UCS4 maxchar = 127; enum PyUnicode_Kind rkind; void *rdata; Py_UCS4 re_sign_char = '\0'; Py_UCS4 im_sign_char = '\0'; int re_float_type; /* Used to see if we have a nan, inf, or regular float. */ int im_float_type; int add_parens = 0; int skip_re = 0; Py_ssize_t lpad; Py_ssize_t rpad; Py_ssize_t total; PyObject *re_unicode_tmp = NULL; PyObject *im_unicode_tmp = NULL; /* Locale settings, either from the actual locale or from a hard-code pseudo-locale */ LocaleInfo locale = STATIC_LOCALE_INFO_INIT; if (format->precision > INT_MAX) { PyErr_SetString(PyExc_ValueError, "precision too big"); goto done; } precision = (int)format->precision; /* Zero padding is not allowed. */ if (format->fill_char == '0') { PyErr_SetString(PyExc_ValueError, "Zero padding is not allowed in complex format " "specifier"); goto done; } /* Neither is '=' alignment . */ if (format->align == '=') { PyErr_SetString(PyExc_ValueError, "'=' alignment flag is not allowed in complex format " "specifier"); goto done; } re = PyComplex_RealAsDouble(value); if (re == -1.0 && PyErr_Occurred()) goto done; im = PyComplex_ImagAsDouble(value); if (im == -1.0 && PyErr_Occurred()) goto done; if (format->alternate) flags |= Py_DTSF_ALT; if (type == '\0') { /* Omitted type specifier. Should be like str(self). */ type = 'r'; default_precision = 0; if (re == 0.0 && copysign(1.0, re) == 1.0) skip_re = 1; else add_parens = 1; } if (type == 'n') /* 'n' is the same as 'g', except for the locale used to format the result. We take care of that later. */ type = 'g'; if (precision < 0) precision = default_precision; else if (type == 'r') type = 'g'; /* Cast "type", because if we're in unicode we need to pass an 8-bit char. This is safe, because we've restricted what "type" can be. */ re_buf = PyOS_double_to_string(re, (char)type, precision, flags, &re_float_type); if (re_buf == NULL) goto done; im_buf = PyOS_double_to_string(im, (char)type, precision, flags, &im_float_type); if (im_buf == NULL) goto done; n_re_digits = strlen(re_buf); n_im_digits = strlen(im_buf); /* Since there is no unicode version of PyOS_double_to_string, just use the 8 bit version and then convert to unicode. */ re_unicode_tmp = _PyUnicode_FromASCII(re_buf, n_re_digits); if (re_unicode_tmp == NULL) goto done; i_re = 0; im_unicode_tmp = _PyUnicode_FromASCII(im_buf, n_im_digits); if (im_unicode_tmp == NULL) goto done; i_im = 0; /* Is a sign character present in the output? If so, remember it and skip it */ if (PyUnicode_READ_CHAR(re_unicode_tmp, i_re) == '-') { re_sign_char = '-'; ++i_re; --n_re_digits; } if (PyUnicode_READ_CHAR(im_unicode_tmp, i_im) == '-') { im_sign_char = '-'; ++i_im; --n_im_digits; } /* Determine if we have any "remainder" (after the digits, might include decimal or exponent or both (or neither)) */ parse_number(re_unicode_tmp, i_re, i_re + n_re_digits, &n_re_remainder, &re_has_decimal); parse_number(im_unicode_tmp, i_im, i_im + n_im_digits, &n_im_remainder, &im_has_decimal); /* Determine the grouping, separator, and decimal point, if any. */ if (get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE : format->thousands_separators, &locale) == -1) goto done; /* Turn off any padding. We'll do it later after we've composed the numbers without padding. */ tmp_format.fill_char = '\0'; tmp_format.align = '<'; tmp_format.width = -1; /* Calculate how much memory we'll need. */ n_re_total = calc_number_widths(&re_spec, 0, re_sign_char, re_unicode_tmp, i_re, i_re + n_re_digits, n_re_remainder, re_has_decimal, &locale, &tmp_format, &maxchar); if (n_re_total == -1) { goto done; } /* Same formatting, but always include a sign, unless the real part is * going to be omitted, in which case we use whatever sign convention was * requested by the original format. */ if (!skip_re) tmp_format.sign = '+'; n_im_total = calc_number_widths(&im_spec, 0, im_sign_char, im_unicode_tmp, i_im, i_im + n_im_digits, n_im_remainder, im_has_decimal, &locale, &tmp_format, &maxchar); if (n_im_total == -1) { goto done; } if (skip_re) n_re_total = 0; /* Add 1 for the 'j', and optionally 2 for parens. */ calc_padding(n_re_total + n_im_total + 1 + add_parens * 2, format->width, format->align, &lpad, &rpad, &total); if (lpad || rpad) maxchar = Py_MAX(maxchar, format->fill_char); if (_PyUnicodeWriter_Prepare(writer, total, maxchar) == -1) goto done; rkind = writer->kind; rdata = writer->data; /* Populate the memory. First, the padding. */ result = fill_padding(writer, n_re_total + n_im_total + 1 + add_parens * 2, format->fill_char, lpad, rpad); if (result == -1) goto done; if (add_parens) { PyUnicode_WRITE(rkind, rdata, writer->pos, '('); writer->pos++; } if (!skip_re) { result = fill_number(writer, &re_spec, re_unicode_tmp, i_re, i_re + n_re_digits, NULL, 0, 0, &locale, 0); if (result == -1) goto done; } result = fill_number(writer, &im_spec, im_unicode_tmp, i_im, i_im + n_im_digits, NULL, 0, 0, &locale, 0); if (result == -1) goto done; PyUnicode_WRITE(rkind, rdata, writer->pos, 'j'); writer->pos++; if (add_parens) { PyUnicode_WRITE(rkind, rdata, writer->pos, ')'); writer->pos++; } writer->pos += rpad; done: PyMem_Free(re_buf); PyMem_Free(im_buf); Py_XDECREF(re_unicode_tmp); Py_XDECREF(im_unicode_tmp); free_locale_info(&locale); return result; } /************************************************************************/ /*********** built in formatters ****************************************/ /************************************************************************/ static int format_obj(PyObject *obj, _PyUnicodeWriter *writer) { PyObject *str; int err; str = PyObject_Str(obj); if (str == NULL) return -1; err = _PyUnicodeWriter_WriteStr(writer, str); Py_DECREF(str); return err; } int _PyUnicode_FormatAdvancedWriter(_PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end) { InternalFormatSpec format; assert(PyUnicode_Check(obj)); /* check for the special case of zero length format spec, make it equivalent to str(obj) */ if (start == end) { if (PyUnicode_CheckExact(obj)) return _PyUnicodeWriter_WriteStr(writer, obj); else return format_obj(obj, writer); } /* parse the format_spec */ if (!parse_internal_render_format_spec(format_spec, start, end, &format, 's', '<')) return -1; /* type conversion? */ switch (format.type) { case 's': /* no type conversion needed, already a string. do the formatting */ return format_string_internal(obj, &format, writer); default: /* unknown */ unknown_presentation_type(format.type, obj->ob_type->tp_name); return -1; } } int _PyLong_FormatAdvancedWriter(_PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end) { PyObject *tmp = NULL, *str = NULL; InternalFormatSpec format; int result = -1; /* check for the special case of zero length format spec, make it equivalent to str(obj) */ if (start == end) { if (PyLong_CheckExact(obj)) return _PyLong_FormatWriter(writer, obj, 10, 0); else return format_obj(obj, writer); } /* parse the format_spec */ if (!parse_internal_render_format_spec(format_spec, start, end, &format, 'd', '>')) goto done; /* type conversion? */ switch (format.type) { case 'b': case 'c': case 'd': case 'o': case 'x': case 'X': case 'n': /* no type conversion needed, already an int. do the formatting */ result = format_long_internal(obj, &format, writer); break; case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': case '%': /* convert to float */ tmp = PyNumber_Float(obj); if (tmp == NULL) goto done; result = format_float_internal(tmp, &format, writer); break; default: /* unknown */ unknown_presentation_type(format.type, obj->ob_type->tp_name); goto done; } done: Py_XDECREF(tmp); Py_XDECREF(str); return result; } int _PyFloat_FormatAdvancedWriter(_PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end) { InternalFormatSpec format; /* check for the special case of zero length format spec, make it equivalent to str(obj) */ if (start == end) return format_obj(obj, writer); /* parse the format_spec */ if (!parse_internal_render_format_spec(format_spec, start, end, &format, '\0', '>')) return -1; /* type conversion? */ switch (format.type) { case '\0': /* No format code: like 'g', but with at least one decimal. */ case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': case 'n': case '%': /* no conversion, already a float. do the formatting */ return format_float_internal(obj, &format, writer); default: /* unknown */ unknown_presentation_type(format.type, obj->ob_type->tp_name); return -1; } } int _PyComplex_FormatAdvancedWriter(_PyUnicodeWriter *writer, PyObject *obj, PyObject *format_spec, Py_ssize_t start, Py_ssize_t end) { InternalFormatSpec format; /* check for the special case of zero length format spec, make it equivalent to str(obj) */ if (start == end) return format_obj(obj, writer); /* parse the format_spec */ if (!parse_internal_render_format_spec(format_spec, start, end, &format, '\0', '>')) return -1; /* type conversion? */ switch (format.type) { case '\0': /* No format code: like 'g', but with at least one decimal. */ case 'e': case 'E': case 'f': case 'F': case 'g': case 'G': case 'n': /* no conversion, already a complex. do the formatting */ return format_complex_internal(obj, &format, writer); default: /* unknown */ unknown_presentation_type(format.type, obj->ob_type->tp_name); return -1; } }
53,009
1,616
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/initmain.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ PYTHON_PROVIDE("__main__"); void _Py_InitMain(PyInterpreterState *interp) { PyObject *m, *d, *loader, *ann_dict; m = PyImport_AddModule("__main__"); if (m == NULL) Py_FatalError("can't create __main__ module"); d = PyModule_GetDict(m); ann_dict = PyDict_New(); if ((ann_dict == NULL) || (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) { Py_FatalError("Failed to initialize __main__.__annotations__"); } Py_DECREF(ann_dict); if (PyDict_GetItemString(d, "__builtins__") == NULL) { PyObject *bimod = PyImport_ImportModule("builtins"); if (bimod == NULL) { Py_FatalError("Failed to retrieve builtins module"); } if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) { Py_FatalError("Failed to initialize __main__.__builtins__"); } Py_DECREF(bimod); } /* Main is a little special - imp.is_builtin("__main__") will return * False, but BuiltinImporter is still the most appropriate initial * setting for its __loader__ attribute. A more suitable value will * be set if __main__ gets further initialized later in the startup * process. */ loader = PyDict_GetItemString(d, "__loader__"); if (loader == NULL || loader == Py_None) { PyObject *loader = PyObject_GetAttrString(interp->importlib, "BuiltinImporter"); if (loader == NULL) { Py_FatalError("Failed to retrieve BuiltinImporter"); } if (PyDict_SetItemString(d, "__loader__", loader) < 0) { Py_FatalError("Failed to initialize __main__.__loader__"); } Py_DECREF(loader); } }
2,868
60
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pystrcmp.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyctype.h" /* clang-format off */ /* Cross platform case insensitive string compare functions */ int PyOS_mystrnicmp(const char *s1, const char *s2, Py_ssize_t size) { if (size == 0) return 0; while ((--size > 0) && (Py_TOLOWER(*s1) == Py_TOLOWER(*s2))) { if (!*s1++ || !*s2++) break; } return Py_TOLOWER(*s1) - Py_TOLOWER(*s2); } int PyOS_mystricmp(const char *s1, const char *s2) { while (*s1 && (Py_TOLOWER((unsigned)*s1++) == Py_TOLOWER((unsigned)*s2++))) { } return (Py_TOLOWER((unsigned)*s1) - Py_TOLOWER((unsigned)*s2)); }
1,501
34
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/ceval_gil.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 "libc/calls/struct/timespec.h" #include "libc/calls/struct/timeval.h" #include "libc/thread/thread2.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Python/condvar.h" /* clang-format off */ /* * Implementation of the Global Interpreter Lock (GIL). */ /* First some general settings */ /* microseconds (the Python API uses seconds, though) */ #define DEFAULT_INTERVAL 5000 static unsigned long gil_interval = DEFAULT_INTERVAL; #define INTERVAL (gil_interval >= 1 ? gil_interval : 1) /* Enable if you want to force the switching of threads at least every `gil_interval` */ #undef FORCE_SWITCHING #define FORCE_SWITCHING /* Notes about the implementation: - The GIL is just a boolean variable (gil_locked) whose access is protected by a mutex (gil_mutex), and whose changes are signalled by a condition variable (gil_cond). gil_mutex is taken for short periods of time, and therefore mostly uncontended. - In the GIL-holding thread, the main loop (PyEval_EvalFrameEx) must be able to release the GIL on demand by another thread. A volatile boolean variable (gil_drop_request) is used for that purpose, which is checked at every turn of the eval loop. That variable is set after a wait of `interval` microseconds on `gil_cond` has timed out. [Actually, another volatile boolean variable (eval_breaker) is used which ORs several conditions into one. Volatile booleans are sufficient as inter-thread signalling means since Python is run on cache-coherent architectures only.] - A thread wanting to take the GIL will first let pass a given amount of time (`interval` microseconds) before setting gil_drop_request. This encourages a defined switching period, but doesn't enforce it since opcodes can take an arbitrary time to execute. The `interval` value is available for the user to read and modify using the Python API `sys.{get,set}switchinterval()`. - When a thread releases the GIL and gil_drop_request is set, that thread ensures that another GIL-awaiting thread gets scheduled. It does so by waiting on a condition variable (switch_cond) until the value of gil_last_holder is changed to something else than its own thread state pointer, indicating that another thread was able to take the GIL. This is meant to prohibit the latency-adverse behaviour on multi-core machines where one thread would speculatively release the GIL, but still run and end up being the first to re-acquire it, making the "timeslices" much longer than expected. (Note: this mechanism is enabled with FORCE_SWITCHING above) */ #ifndef Py_HAVE_CONDVAR #error You need either a POSIX-compatible or a Windows system! #endif #define MUTEX_T PyMUTEX_T #define MUTEX_INIT(mut) \ if (PyMUTEX_INIT(&(mut))) { \ Py_FatalError("PyMUTEX_INIT(" #mut ") failed"); }; #define MUTEX_FINI(mut) \ if (PyMUTEX_FINI(&(mut))) { \ Py_FatalError("PyMUTEX_FINI(" #mut ") failed"); }; #define MUTEX_LOCK(mut) \ if (PyMUTEX_LOCK(&(mut))) { \ Py_FatalError("PyMUTEX_LOCK(" #mut ") failed"); }; #define MUTEX_UNLOCK(mut) \ if (PyMUTEX_UNLOCK(&(mut))) { \ Py_FatalError("PyMUTEX_UNLOCK(" #mut ") failed"); }; #define COND_T PyCOND_T #define COND_INIT(cond) \ if (PyCOND_INIT(&(cond))) { \ Py_FatalError("PyCOND_INIT(" #cond ") failed"); }; #define COND_FINI(cond) \ if (PyCOND_FINI(&(cond))) { \ Py_FatalError("PyCOND_FINI(" #cond ") failed"); }; #define COND_SIGNAL(cond) \ if (PyCOND_SIGNAL(&(cond))) { \ Py_FatalError("PyCOND_SIGNAL(" #cond ") failed"); }; #define COND_WAIT(cond, mut) \ if (PyCOND_WAIT(&(cond), &(mut))) { \ Py_FatalError("PyCOND_WAIT(" #cond ") failed"); }; #define COND_TIMED_WAIT(cond, mut, microseconds, timeout_result) \ { \ int r = PyCOND_TIMEDWAIT(&(cond), &(mut), (microseconds)); \ if (r < 0) \ Py_FatalError("PyCOND_WAIT(" #cond ") failed"); \ if (r) /* 1 == timeout, 2 == impl. can't say, so assume timeout */ \ timeout_result = 1; \ else \ timeout_result = 0; \ } \ /* Whether the GIL is already taken (-1 if uninitialized). This is atomic because it can be read without any lock taken in ceval.c. */ static _Py_atomic_int gil_locked = {-1}; /* Number of GIL switches since the beginning. */ static unsigned long gil_switch_number = 0; /* Last PyThreadState holding / having held the GIL. This helps us know whether anyone else was scheduled after we dropped the GIL. */ static _Py_atomic_address gil_last_holder = {0}; /* This condition variable allows one or several threads to wait until the GIL is released. In addition, the mutex also protects the above variables. */ static COND_T gil_cond; static MUTEX_T gil_mutex; #ifdef FORCE_SWITCHING /* This condition variable helps the GIL-releasing thread wait for a GIL-awaiting thread to be scheduled and take the GIL. */ static COND_T switch_cond; static MUTEX_T switch_mutex; #endif static int gil_created(void) { return _Py_atomic_load_explicit(&gil_locked, _Py_memory_order_acquire) >= 0; } static void create_gil(void) { MUTEX_INIT(gil_mutex); #ifdef FORCE_SWITCHING MUTEX_INIT(switch_mutex); #endif COND_INIT(gil_cond); #ifdef FORCE_SWITCHING COND_INIT(switch_cond); #endif _Py_atomic_store_relaxed(&gil_last_holder, 0); _Py_ANNOTATE_RWLOCK_CREATE(&gil_locked); _Py_atomic_store_explicit(&gil_locked, 0, _Py_memory_order_release); } static void destroy_gil(void) { /* some pthread-like implementations tie the mutex to the cond * and must have the cond destroyed first. */ COND_FINI(gil_cond); MUTEX_FINI(gil_mutex); #ifdef FORCE_SWITCHING COND_FINI(switch_cond); MUTEX_FINI(switch_mutex); #endif _Py_atomic_store_explicit(&gil_locked, -1, _Py_memory_order_release); _Py_ANNOTATE_RWLOCK_DESTROY(&gil_locked); } static void recreate_gil(void) { _Py_ANNOTATE_RWLOCK_DESTROY(&gil_locked); /* XXX should we destroy the old OS resources here? */ create_gil(); } static void drop_gil(PyThreadState *tstate) { if (!_Py_atomic_load_relaxed(&gil_locked)) Py_FatalError("drop_gil: GIL is not locked"); /* tstate is allowed to be NULL (early interpreter init) */ if (tstate != NULL) { /* Sub-interpreter support: threads might have been switched under our feet using PyThreadState_Swap(). Fix the GIL last holder variable so that our heuristics work. */ _Py_atomic_store_relaxed(&gil_last_holder, (uintptr_t)tstate); } MUTEX_LOCK(gil_mutex); _Py_ANNOTATE_RWLOCK_RELEASED(&gil_locked, /*is_write=*/1); _Py_atomic_store_relaxed(&gil_locked, 0); COND_SIGNAL(gil_cond); MUTEX_UNLOCK(gil_mutex); #ifdef FORCE_SWITCHING if (_Py_atomic_load_relaxed(&gil_drop_request) && tstate != NULL) { MUTEX_LOCK(switch_mutex); /* Not switched yet => wait */ if ((PyThreadState*)_Py_atomic_load_relaxed(&gil_last_holder) == tstate) { RESET_GIL_DROP_REQUEST(); /* NOTE: if COND_WAIT does not atomically start waiting when releasing the mutex, another thread can run through, take the GIL and drop it again, and reset the condition before we even had a chance to wait for it. */ COND_WAIT(switch_cond, switch_mutex); } MUTEX_UNLOCK(switch_mutex); } #endif } static void take_gil(PyThreadState *tstate) { int err; if (tstate == NULL) Py_FatalError("take_gil: NULL tstate"); err = errno; MUTEX_LOCK(gil_mutex); if (!_Py_atomic_load_relaxed(&gil_locked)) goto _ready; while (_Py_atomic_load_relaxed(&gil_locked)) { int timed_out = 0; unsigned long saved_switchnum; saved_switchnum = gil_switch_number; COND_TIMED_WAIT(gil_cond, gil_mutex, INTERVAL, timed_out); /* If we timed out and no switch occurred in the meantime, it is time to ask the GIL-holding thread to drop it. */ if (timed_out && _Py_atomic_load_relaxed(&gil_locked) && gil_switch_number == saved_switchnum) { SET_GIL_DROP_REQUEST(); } } _ready: #ifdef FORCE_SWITCHING /* This mutex must be taken before modifying gil_last_holder (see drop_gil()). */ MUTEX_LOCK(switch_mutex); #endif /* We now hold the GIL */ _Py_atomic_store_relaxed(&gil_locked, 1); _Py_ANNOTATE_RWLOCK_ACQUIRED(&gil_locked, /*is_write=*/1); if (tstate != (PyThreadState*)_Py_atomic_load_relaxed(&gil_last_holder)) { _Py_atomic_store_relaxed(&gil_last_holder, (uintptr_t)tstate); ++gil_switch_number; } #ifdef FORCE_SWITCHING COND_SIGNAL(switch_cond); MUTEX_UNLOCK(switch_mutex); #endif if (_Py_atomic_load_relaxed(&gil_drop_request)) { RESET_GIL_DROP_REQUEST(); } if (tstate->async_exc != NULL) { _PyEval_SignalAsyncExc(); } MUTEX_UNLOCK(gil_mutex); errno = err; } void _PyEval_SetSwitchInterval(unsigned long microseconds) { gil_interval = microseconds; } unsigned long _PyEval_GetSwitchInterval() { return gil_interval; }
10,128
279
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/ast.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/ast.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/compile.h" #include "third_party/python/Include/complexobject.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/node.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pyport.h" #include "third_party/python/Include/pystrtod.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/sliceobject.h" #include "third_party/python/Include/token.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/warnings.h" #include "third_party/python/Modules/unicodedata.h" /* clang-format off */ static int validate_stmts(asdl_seq *); static int validate_exprs(asdl_seq *, expr_context_ty, int); static int validate_nonempty_seq(asdl_seq *, const char *, const char *); static int validate_stmt(stmt_ty); static int validate_expr(expr_ty, expr_context_ty); static int validate_comprehension(asdl_seq *gens) { int i; if (!asdl_seq_LEN(gens)) { PyErr_SetString(PyExc_ValueError, "comprehension with no generators"); return 0; } for (i = 0; i < asdl_seq_LEN(gens); i++) { comprehension_ty comp = asdl_seq_GET(gens, i); if (!validate_expr(comp->target, Store) || !validate_expr(comp->iter, Load) || !validate_exprs(comp->ifs, Load, 0)) return 0; } return 1; } static int validate_slice(slice_ty slice) { switch (slice->kind) { case Slice_kind: return (!slice->v.Slice.lower || validate_expr(slice->v.Slice.lower, Load)) && (!slice->v.Slice.upper || validate_expr(slice->v.Slice.upper, Load)) && (!slice->v.Slice.step || validate_expr(slice->v.Slice.step, Load)); case ExtSlice_kind: { int i; if (!validate_nonempty_seq(slice->v.ExtSlice.dims, "dims", "ExtSlice")) return 0; for (i = 0; i < asdl_seq_LEN(slice->v.ExtSlice.dims); i++) if (!validate_slice(asdl_seq_GET(slice->v.ExtSlice.dims, i))) return 0; return 1; } case Index_kind: return validate_expr(slice->v.Index.value, Load); default: PyErr_SetString(PyExc_SystemError, "unknown slice node"); return 0; } } static int validate_keywords(asdl_seq *keywords) { int i; for (i = 0; i < asdl_seq_LEN(keywords); i++) if (!validate_expr(((keyword_ty)asdl_seq_GET(keywords, i))->value, Load)) return 0; return 1; } static int validate_args(asdl_seq *args) { int i; for (i = 0; i < asdl_seq_LEN(args); i++) { arg_ty arg = asdl_seq_GET(args, i); if (arg->annotation && !validate_expr(arg->annotation, Load)) return 0; } return 1; } static const char * expr_context_name(expr_context_ty ctx) { switch (ctx) { case Load: return "Load"; case Store: return "Store"; case Del: return "Del"; case AugLoad: return "AugLoad"; case AugStore: return "AugStore"; case Param: return "Param"; default: assert(0); return "(unknown)"; } } static int validate_arguments(arguments_ty args) { if (!validate_args(args->args)) return 0; if (args->vararg && args->vararg->annotation && !validate_expr(args->vararg->annotation, Load)) { return 0; } if (!validate_args(args->kwonlyargs)) return 0; if (args->kwarg && args->kwarg->annotation && !validate_expr(args->kwarg->annotation, Load)) { return 0; } if (asdl_seq_LEN(args->defaults) > asdl_seq_LEN(args->args)) { PyErr_SetString(PyExc_ValueError, "more positional defaults than args on arguments"); return 0; } if (asdl_seq_LEN(args->kw_defaults) != asdl_seq_LEN(args->kwonlyargs)) { PyErr_SetString(PyExc_ValueError, "length of kwonlyargs is not the same as " "kw_defaults on arguments"); return 0; } return validate_exprs(args->defaults, Load, 0) && validate_exprs(args->kw_defaults, Load, 1); } static int validate_constant(PyObject *value) { if (value == Py_None || value == Py_Ellipsis) return 1; if (PyLong_CheckExact(value) || PyFloat_CheckExact(value) || PyComplex_CheckExact(value) || PyBool_Check(value) || PyUnicode_CheckExact(value) || PyBytes_CheckExact(value)) return 1; if (PyTuple_CheckExact(value) || PyFrozenSet_CheckExact(value)) { PyObject *it; it = PyObject_GetIter(value); if (it == NULL) return 0; while (1) { PyObject *item = PyIter_Next(it); if (item == NULL) { if (PyErr_Occurred()) { Py_DECREF(it); return 0; } break; } if (!validate_constant(item)) { Py_DECREF(it); Py_DECREF(item); return 0; } Py_DECREF(item); } Py_DECREF(it); return 1; } return 0; } static int validate_expr(expr_ty exp, expr_context_ty ctx) { int check_ctx = 1; expr_context_ty actual_ctx; /* First check expression context. */ switch (exp->kind) { case Attribute_kind: actual_ctx = exp->v.Attribute.ctx; break; case Subscript_kind: actual_ctx = exp->v.Subscript.ctx; break; case Starred_kind: actual_ctx = exp->v.Starred.ctx; break; case Name_kind: actual_ctx = exp->v.Name.ctx; break; case List_kind: actual_ctx = exp->v.List.ctx; break; case Tuple_kind: actual_ctx = exp->v.Tuple.ctx; break; default: if (ctx != Load) { PyErr_Format(PyExc_ValueError, "expression which can't be " "assigned to in %s context", expr_context_name(ctx)); return 0; } check_ctx = 0; /* set actual_ctx to prevent gcc warning */ actual_ctx = 0; } if (check_ctx && actual_ctx != ctx) { PyErr_Format(PyExc_ValueError, "expression must have %s context but has %s instead", expr_context_name(ctx), expr_context_name(actual_ctx)); return 0; } /* Now validate expression. */ switch (exp->kind) { case BoolOp_kind: if (asdl_seq_LEN(exp->v.BoolOp.values) < 2) { PyErr_SetString(PyExc_ValueError, "BoolOp with less than 2 values"); return 0; } return validate_exprs(exp->v.BoolOp.values, Load, 0); case BinOp_kind: return validate_expr(exp->v.BinOp.left, Load) && validate_expr(exp->v.BinOp.right, Load); case UnaryOp_kind: return validate_expr(exp->v.UnaryOp.operand, Load); case Lambda_kind: return validate_arguments(exp->v.Lambda.args) && validate_expr(exp->v.Lambda.body, Load); case IfExp_kind: return validate_expr(exp->v.IfExp.test, Load) && validate_expr(exp->v.IfExp.body, Load) && validate_expr(exp->v.IfExp.orelse, Load); case Dict_kind: if (asdl_seq_LEN(exp->v.Dict.keys) != asdl_seq_LEN(exp->v.Dict.values)) { PyErr_SetString(PyExc_ValueError, "Dict doesn't have the same number of keys as values"); return 0; } /* null_ok=1 for keys expressions to allow dict unpacking to work in dict literals, i.e. ``{**{a:b}}`` */ return validate_exprs(exp->v.Dict.keys, Load, /*null_ok=*/ 1) && validate_exprs(exp->v.Dict.values, Load, /*null_ok=*/ 0); case Set_kind: return validate_exprs(exp->v.Set.elts, Load, 0); #define COMP(NAME) \ case NAME ## _kind: \ return validate_comprehension(exp->v.NAME.generators) && \ validate_expr(exp->v.NAME.elt, Load); COMP(ListComp) COMP(SetComp) COMP(GeneratorExp) #undef COMP case DictComp_kind: return validate_comprehension(exp->v.DictComp.generators) && validate_expr(exp->v.DictComp.key, Load) && validate_expr(exp->v.DictComp.value, Load); case Yield_kind: return !exp->v.Yield.value || validate_expr(exp->v.Yield.value, Load); case YieldFrom_kind: return validate_expr(exp->v.YieldFrom.value, Load); case Await_kind: return validate_expr(exp->v.Await.value, Load); case Compare_kind: if (!asdl_seq_LEN(exp->v.Compare.comparators)) { PyErr_SetString(PyExc_ValueError, "Compare with no comparators"); return 0; } if (asdl_seq_LEN(exp->v.Compare.comparators) != asdl_seq_LEN(exp->v.Compare.ops)) { PyErr_SetString(PyExc_ValueError, "Compare has a different number " "of comparators and operands"); return 0; } return validate_exprs(exp->v.Compare.comparators, Load, 0) && validate_expr(exp->v.Compare.left, Load); case Call_kind: return validate_expr(exp->v.Call.func, Load) && validate_exprs(exp->v.Call.args, Load, 0) && validate_keywords(exp->v.Call.keywords); case Constant_kind: if (!validate_constant(exp->v.Constant.value)) { PyErr_Format(PyExc_TypeError, "got an invalid type in Constant: %s", Py_TYPE(exp->v.Constant.value)->tp_name); return 0; } return 1; case Num_kind: { PyObject *n = exp->v.Num.n; if (!PyLong_CheckExact(n) && !PyFloat_CheckExact(n) && !PyComplex_CheckExact(n)) { PyErr_SetString(PyExc_TypeError, "non-numeric type in Num"); return 0; } return 1; } case Str_kind: { PyObject *s = exp->v.Str.s; if (!PyUnicode_CheckExact(s)) { PyErr_SetString(PyExc_TypeError, "non-string type in Str"); return 0; } return 1; } case JoinedStr_kind: return validate_exprs(exp->v.JoinedStr.values, Load, 0); case FormattedValue_kind: if (validate_expr(exp->v.FormattedValue.value, Load) == 0) return 0; if (exp->v.FormattedValue.format_spec) return validate_expr(exp->v.FormattedValue.format_spec, Load); return 1; case Bytes_kind: { PyObject *b = exp->v.Bytes.s; if (!PyBytes_CheckExact(b)) { PyErr_SetString(PyExc_TypeError, "non-bytes type in Bytes"); return 0; } return 1; } case Attribute_kind: return validate_expr(exp->v.Attribute.value, Load); case Subscript_kind: return validate_slice(exp->v.Subscript.slice) && validate_expr(exp->v.Subscript.value, Load); case Starred_kind: return validate_expr(exp->v.Starred.value, ctx); case List_kind: return validate_exprs(exp->v.List.elts, ctx, 0); case Tuple_kind: return validate_exprs(exp->v.Tuple.elts, ctx, 0); /* These last cases don't have any checking. */ case Name_kind: case NameConstant_kind: case Ellipsis_kind: return 1; default: PyErr_SetString(PyExc_SystemError, "unexpected expression"); return 0; } } static int validate_nonempty_seq(asdl_seq *seq, const char *what, const char *owner) { if (asdl_seq_LEN(seq)) return 1; PyErr_Format(PyExc_ValueError, "empty %s on %s", what, owner); return 0; } static int validate_assignlist(asdl_seq *targets, expr_context_ty ctx) { return validate_nonempty_seq(targets, "targets", ctx == Del ? "Delete" : "Assign") && validate_exprs(targets, ctx, 0); } static int validate_body(asdl_seq *body, const char *owner) { return validate_nonempty_seq(body, "body", owner) && validate_stmts(body); } static int validate_stmt(stmt_ty stmt) { int i; switch (stmt->kind) { case FunctionDef_kind: return validate_body(stmt->v.FunctionDef.body, "FunctionDef") && validate_arguments(stmt->v.FunctionDef.args) && validate_exprs(stmt->v.FunctionDef.decorator_list, Load, 0) && (!stmt->v.FunctionDef.returns || validate_expr(stmt->v.FunctionDef.returns, Load)); case ClassDef_kind: return validate_body(stmt->v.ClassDef.body, "ClassDef") && validate_exprs(stmt->v.ClassDef.bases, Load, 0) && validate_keywords(stmt->v.ClassDef.keywords) && validate_exprs(stmt->v.ClassDef.decorator_list, Load, 0); case Return_kind: return !stmt->v.Return.value || validate_expr(stmt->v.Return.value, Load); case Delete_kind: return validate_assignlist(stmt->v.Delete.targets, Del); case Assign_kind: return validate_assignlist(stmt->v.Assign.targets, Store) && validate_expr(stmt->v.Assign.value, Load); case AugAssign_kind: return validate_expr(stmt->v.AugAssign.target, Store) && validate_expr(stmt->v.AugAssign.value, Load); case AnnAssign_kind: if (stmt->v.AnnAssign.target->kind != Name_kind && stmt->v.AnnAssign.simple) { PyErr_SetString(PyExc_TypeError, "AnnAssign with simple non-Name target"); return 0; } return validate_expr(stmt->v.AnnAssign.target, Store) && (!stmt->v.AnnAssign.value || validate_expr(stmt->v.AnnAssign.value, Load)) && validate_expr(stmt->v.AnnAssign.annotation, Load); case For_kind: return validate_expr(stmt->v.For.target, Store) && validate_expr(stmt->v.For.iter, Load) && validate_body(stmt->v.For.body, "For") && validate_stmts(stmt->v.For.orelse); case AsyncFor_kind: return validate_expr(stmt->v.AsyncFor.target, Store) && validate_expr(stmt->v.AsyncFor.iter, Load) && validate_body(stmt->v.AsyncFor.body, "AsyncFor") && validate_stmts(stmt->v.AsyncFor.orelse); case While_kind: return validate_expr(stmt->v.While.test, Load) && validate_body(stmt->v.While.body, "While") && validate_stmts(stmt->v.While.orelse); case If_kind: return validate_expr(stmt->v.If.test, Load) && validate_body(stmt->v.If.body, "If") && validate_stmts(stmt->v.If.orelse); case With_kind: if (!validate_nonempty_seq(stmt->v.With.items, "items", "With")) return 0; for (i = 0; i < asdl_seq_LEN(stmt->v.With.items); i++) { withitem_ty item = asdl_seq_GET(stmt->v.With.items, i); if (!validate_expr(item->context_expr, Load) || (item->optional_vars && !validate_expr(item->optional_vars, Store))) return 0; } return validate_body(stmt->v.With.body, "With"); case AsyncWith_kind: if (!validate_nonempty_seq(stmt->v.AsyncWith.items, "items", "AsyncWith")) return 0; for (i = 0; i < asdl_seq_LEN(stmt->v.AsyncWith.items); i++) { withitem_ty item = asdl_seq_GET(stmt->v.AsyncWith.items, i); if (!validate_expr(item->context_expr, Load) || (item->optional_vars && !validate_expr(item->optional_vars, Store))) return 0; } return validate_body(stmt->v.AsyncWith.body, "AsyncWith"); case Raise_kind: if (stmt->v.Raise.exc) { return validate_expr(stmt->v.Raise.exc, Load) && (!stmt->v.Raise.cause || validate_expr(stmt->v.Raise.cause, Load)); } if (stmt->v.Raise.cause) { PyErr_SetString(PyExc_ValueError, "Raise with cause but no exception"); return 0; } return 1; case Try_kind: if (!validate_body(stmt->v.Try.body, "Try")) return 0; if (!asdl_seq_LEN(stmt->v.Try.handlers) && !asdl_seq_LEN(stmt->v.Try.finalbody)) { PyErr_SetString(PyExc_ValueError, "Try has neither except handlers nor finalbody"); return 0; } if (!asdl_seq_LEN(stmt->v.Try.handlers) && asdl_seq_LEN(stmt->v.Try.orelse)) { PyErr_SetString(PyExc_ValueError, "Try has orelse but no except handlers"); return 0; } for (i = 0; i < asdl_seq_LEN(stmt->v.Try.handlers); i++) { excepthandler_ty handler = asdl_seq_GET(stmt->v.Try.handlers, i); if ((handler->v.ExceptHandler.type && !validate_expr(handler->v.ExceptHandler.type, Load)) || !validate_body(handler->v.ExceptHandler.body, "ExceptHandler")) return 0; } return (!asdl_seq_LEN(stmt->v.Try.finalbody) || validate_stmts(stmt->v.Try.finalbody)) && (!asdl_seq_LEN(stmt->v.Try.orelse) || validate_stmts(stmt->v.Try.orelse)); case Assert_kind: return validate_expr(stmt->v.Assert.test, Load) && (!stmt->v.Assert.msg || validate_expr(stmt->v.Assert.msg, Load)); case Import_kind: return validate_nonempty_seq(stmt->v.Import.names, "names", "Import"); case ImportFrom_kind: if (stmt->v.ImportFrom.level < 0) { PyErr_SetString(PyExc_ValueError, "Negative ImportFrom level"); return 0; } return validate_nonempty_seq(stmt->v.ImportFrom.names, "names", "ImportFrom"); case Global_kind: return validate_nonempty_seq(stmt->v.Global.names, "names", "Global"); case Nonlocal_kind: return validate_nonempty_seq(stmt->v.Nonlocal.names, "names", "Nonlocal"); case Expr_kind: return validate_expr(stmt->v.Expr.value, Load); case AsyncFunctionDef_kind: return validate_body(stmt->v.AsyncFunctionDef.body, "AsyncFunctionDef") && validate_arguments(stmt->v.AsyncFunctionDef.args) && validate_exprs(stmt->v.AsyncFunctionDef.decorator_list, Load, 0) && (!stmt->v.AsyncFunctionDef.returns || validate_expr(stmt->v.AsyncFunctionDef.returns, Load)); case Pass_kind: case Break_kind: case Continue_kind: return 1; default: PyErr_SetString(PyExc_SystemError, "unexpected statement"); return 0; } } static int validate_stmts(asdl_seq *seq) { int i; for (i = 0; i < asdl_seq_LEN(seq); i++) { stmt_ty stmt = asdl_seq_GET(seq, i); if (stmt) { if (!validate_stmt(stmt)) return 0; } else { PyErr_SetString(PyExc_ValueError, "None disallowed in statement list"); return 0; } } return 1; } static int validate_exprs(asdl_seq *exprs, expr_context_ty ctx, int null_ok) { int i; for (i = 0; i < asdl_seq_LEN(exprs); i++) { expr_ty expr = asdl_seq_GET(exprs, i); if (expr) { if (!validate_expr(expr, ctx)) return 0; } else if (!null_ok) { PyErr_SetString(PyExc_ValueError, "None disallowed in expression list"); return 0; } } return 1; } int PyAST_Validate(mod_ty mod) { int res = 0; switch (mod->kind) { case Module_kind: res = validate_stmts(mod->v.Module.body); break; case Interactive_kind: res = validate_stmts(mod->v.Interactive.body); break; case Expression_kind: res = validate_expr(mod->v.Expression.body, Load); break; case Suite_kind: PyErr_SetString(PyExc_ValueError, "Suite is not valid in the CPython compiler"); break; default: PyErr_SetString(PyExc_SystemError, "impossible module node"); res = 0; break; } return res; } /* This is done here, so defines like "test" don't interfere with AST use above. */ #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/parsetok.h" #include "third_party/python/Include/graminit.h" /* Data structure used internally */ struct compiling { PyArena *c_arena; /* Arena for allocating memory. */ PyObject *c_filename; /* filename */ }; static asdl_seq *seq_for_testlist(struct compiling *, const node *); static expr_ty ast_for_expr(struct compiling *, const node *); static stmt_ty ast_for_stmt(struct compiling *, const node *); static asdl_seq *ast_for_suite(struct compiling *, const node *); static asdl_seq *ast_for_exprlist(struct compiling *, const node *, expr_context_ty); static expr_ty ast_for_testlist(struct compiling *, const node *); static stmt_ty ast_for_classdef(struct compiling *, const node *, asdl_seq *); static stmt_ty ast_for_with_stmt(struct compiling *, const node *, int); static stmt_ty ast_for_for_stmt(struct compiling *, const node *, int); /* Note different signature for ast_for_call */ static expr_ty ast_for_call(struct compiling *, const node *, expr_ty); static PyObject *parsenumber(struct compiling *, const char *); static expr_ty parsestrplus(struct compiling *, const node *n); #define COMP_GENEXP 0 #define COMP_LISTCOMP 1 #define COMP_SETCOMP 2 static identifier new_identifier(const char *n, struct compiling *c) { PyObject *id, *id2; if (!(id = PyUnicode_DecodeUTF8(n, strlen(n), NULL))) return NULL; /* PyUnicode_DecodeUTF8 should always return a ready string. */ assert(PyUnicode_IS_READY(id)); /* Check whether there are non-ASCII characters in the identifier; if so, normalize to NFKC. */ if (!PyUnicode_IS_ASCII(id) && !_PyUnicode_IsNormalized(0, id, 1, 1)) { id2 = _PyUnicode_NfcNfkc(0, id, 1); Py_DECREF(id); if (!id2) return NULL; if (!PyUnicode_Check(id2)) { PyErr_Format(PyExc_TypeError, "unicodedata.normalize() must return " " a string, not %.200s", Py_TYPE(id2)->tp_name); Py_DECREF(id2); return NULL; } id = id2; } PyUnicode_InternInPlace(&id); if (PyArena_AddPyObject(c->c_arena, id) < 0) { Py_DECREF(id); return NULL; } return id; } #define NEW_IDENTIFIER(n) new_identifier(STR(n), c) static int ast_error(struct compiling *c, const node *n, const char *errmsg) { PyObject *value, *errstr, *loc, *tmp; loc = PyErr_ProgramTextObject(c->c_filename, LINENO(n)); if (!loc) { Py_INCREF(Py_None); loc = Py_None; } tmp = Py_BuildValue("(OiiN)", c->c_filename, LINENO(n), n->n_col_offset, loc); if (!tmp) return 0; errstr = PyUnicode_FromString(errmsg); if (!errstr) { Py_DECREF(tmp); return 0; } value = PyTuple_Pack(2, errstr, tmp); Py_DECREF(errstr); Py_DECREF(tmp); if (value) { PyErr_SetObject(PyExc_SyntaxError, value); Py_DECREF(value); } return 0; } /* num_stmts() returns number of contained statements. Use this routine to determine how big a sequence is needed for the statements in a parse tree. Its raison d'etre is this bit of grammar: stmt: simple_stmt | compound_stmt simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE A simple_stmt can contain multiple small_stmt elements joined by semicolons. If the arg is a simple_stmt, the number of small_stmt elements is returned. */ static int num_stmts(const node *n) { int i, l; node *ch; switch (TYPE(n)) { case single_input: if (TYPE(CHILD(n, 0)) == NEWLINE) return 0; else return num_stmts(CHILD(n, 0)); case file_input: l = 0; for (i = 0; i < NCH(n); i++) { ch = CHILD(n, i); if (TYPE(ch) == stmt) l += num_stmts(ch); } return l; case stmt: return num_stmts(CHILD(n, 0)); case compound_stmt: return 1; case simple_stmt: return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */ case suite: if (NCH(n) == 1) return num_stmts(CHILD(n, 0)); else { l = 0; for (i = 2; i < (NCH(n) - 1); i++) l += num_stmts(CHILD(n, i)); return l; } default: { char buf[128]; sprintf(buf, "Non-statement found: %d %d", TYPE(n), NCH(n)); Py_FatalError(buf); } } unreachable; } /* Transform the CST rooted at node * to the appropriate AST */ mod_ty PyAST_FromNodeObject(const node *n, PyCompilerFlags *flags, PyObject *filename, PyArena *arena) { int i, j, k, num; asdl_seq *stmts = NULL; stmt_ty s; node *ch; struct compiling c; mod_ty res = NULL; c.c_arena = arena; /* borrowed reference */ c.c_filename = filename; if (TYPE(n) == encoding_decl) n = CHILD(n, 0); k = 0; switch (TYPE(n)) { case file_input: stmts = _Py_asdl_seq_new(num_stmts(n), arena); if (!stmts) goto out; for (i = 0; i < NCH(n) - 1; i++) { ch = CHILD(n, i); if (TYPE(ch) == NEWLINE) continue; REQ(ch, stmt); num = num_stmts(ch); if (num == 1) { s = ast_for_stmt(&c, ch); if (!s) goto out; asdl_seq_SET(stmts, k++, s); } else { ch = CHILD(ch, 0); REQ(ch, simple_stmt); for (j = 0; j < num; j++) { s = ast_for_stmt(&c, CHILD(ch, j * 2)); if (!s) goto out; asdl_seq_SET(stmts, k++, s); } } } res = Module(stmts, arena); break; case eval_input: { expr_ty testlist_ast; /* XXX Why not comp_for here? */ testlist_ast = ast_for_testlist(&c, CHILD(n, 0)); if (!testlist_ast) goto out; res = Expression(testlist_ast, arena); break; } case single_input: if (TYPE(CHILD(n, 0)) == NEWLINE) { stmts = _Py_asdl_seq_new(1, arena); if (!stmts) goto out; asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset, arena)); if (!asdl_seq_GET(stmts, 0)) goto out; res = Interactive(stmts, arena); } else { n = CHILD(n, 0); num = num_stmts(n); stmts = _Py_asdl_seq_new(num, arena); if (!stmts) goto out; if (num == 1) { s = ast_for_stmt(&c, n); if (!s) goto out; asdl_seq_SET(stmts, 0, s); } else { /* Only a simple_stmt can contain multiple statements. */ REQ(n, simple_stmt); for (i = 0; i < NCH(n); i += 2) { if (TYPE(CHILD(n, i)) == NEWLINE) break; s = ast_for_stmt(&c, CHILD(n, i)); if (!s) goto out; asdl_seq_SET(stmts, i / 2, s); } } res = Interactive(stmts, arena); } break; default: PyErr_Format(PyExc_SystemError, "invalid node %d for PyAST_FromNode", TYPE(n)); goto out; } out: return res; } mod_ty PyAST_FromNode(const node *n, PyCompilerFlags *flags, const char *filename_str, PyArena *arena) { mod_ty mod; PyObject *filename; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) return NULL; mod = PyAST_FromNodeObject(n, flags, filename, arena); Py_DECREF(filename); return mod; } /* Return the AST repr. of the operator represented as syntax (|, ^, etc.) */ static operator_ty get_operator(const node *n) { switch (TYPE(n)) { case VBAR: return BitOr; case CIRCUMFLEX: return BitXor; case AMPER: return BitAnd; case LEFTSHIFT: return LShift; case RIGHTSHIFT: return RShift; case PLUS: return Add; case MINUS: return Sub; case STAR: return Mult; case AT: return MatMult; case SLASH: return Div; case DOUBLESLASH: return FloorDiv; case PERCENT: return Mod; default: return (operator_ty)0; } } static const char * const FORBIDDEN[] = { "None", "True", "False", NULL, }; static int forbidden_name(struct compiling *c, identifier name, const node *n, int full_checks) { assert(PyUnicode_Check(name)); if (_PyUnicode_EqualToASCIIString(name, "__debug__")) { ast_error(c, n, "assignment to keyword"); return 1; } if (_PyUnicode_EqualToASCIIString(name, "async") || _PyUnicode_EqualToASCIIString(name, "await")) { PyObject *message = PyUnicode_FromString( "'async' and 'await' will become reserved keywords" " in Python 3.7"); int ret; if (message == NULL) { return 1; } ret = PyErr_WarnExplicitObject( PyExc_DeprecationWarning, message, c->c_filename, LINENO(n), NULL, NULL); Py_DECREF(message); if (ret < 0) { return 1; } } if (full_checks) { const char * const *p; for (p = FORBIDDEN; *p; p++) { if (_PyUnicode_EqualToASCIIString(name, *p)) { ast_error(c, n, "assignment to keyword"); return 1; } } } return 0; } /* Set the context ctx for expr_ty e, recursively traversing e. Only sets context for expr kinds that "can appear in assignment context" (according to ../Parser/Python.asdl). For other expr kinds, it sets an appropriate syntax error and returns false. */ static int set_context(struct compiling *c, expr_ty e, expr_context_ty ctx, const node *n) { asdl_seq *s = NULL; /* If a particular expression type can't be used for assign / delete, set expr_name to its name and an error message will be generated. */ const char* expr_name = NULL; /* The ast defines augmented store and load contexts, but the implementation here doesn't actually use them. The code may be a little more complex than necessary as a result. It also means that expressions in an augmented assignment have a Store context. Consider restructuring so that augmented assignment uses set_context(), too. */ assert(ctx != AugStore && ctx != AugLoad); switch (e->kind) { case Attribute_kind: e->v.Attribute.ctx = ctx; if (ctx == Store && forbidden_name(c, e->v.Attribute.attr, n, 1)) return 0; break; case Subscript_kind: e->v.Subscript.ctx = ctx; break; case Starred_kind: e->v.Starred.ctx = ctx; if (!set_context(c, e->v.Starred.value, ctx, n)) return 0; break; case Name_kind: if (ctx == Store) { if (forbidden_name(c, e->v.Name.id, n, 0)) return 0; /* forbidden_name() calls ast_error() */ } e->v.Name.ctx = ctx; break; case List_kind: e->v.List.ctx = ctx; s = e->v.List.elts; break; case Tuple_kind: e->v.Tuple.ctx = ctx; s = e->v.Tuple.elts; break; case Lambda_kind: expr_name = "lambda"; break; case Call_kind: expr_name = "function call"; break; case BoolOp_kind: case BinOp_kind: case UnaryOp_kind: expr_name = "operator"; break; case GeneratorExp_kind: expr_name = "generator expression"; break; case Yield_kind: case YieldFrom_kind: expr_name = "yield expression"; break; case Await_kind: expr_name = "await expression"; break; case ListComp_kind: expr_name = "list comprehension"; break; case SetComp_kind: expr_name = "set comprehension"; break; case DictComp_kind: expr_name = "dict comprehension"; break; case Dict_kind: case Set_kind: case Num_kind: case Str_kind: case Bytes_kind: case JoinedStr_kind: case FormattedValue_kind: expr_name = "literal"; break; case NameConstant_kind: expr_name = "keyword"; break; case Ellipsis_kind: expr_name = "Ellipsis"; break; case Compare_kind: expr_name = "comparison"; break; case IfExp_kind: expr_name = "conditional expression"; break; default: PyErr_Format(PyExc_SystemError, "unexpected expression in assignment %d (line %d)", e->kind, e->lineno); return 0; } /* Check for error string set by switch */ if (expr_name) { char buf[300]; PyOS_snprintf(buf, sizeof(buf), "can't %s %s", ctx == Store ? "assign to" : "delete", expr_name); return ast_error(c, n, buf); } /* If the LHS is a list or tuple, we need to set the assignment context for all the contained elements. */ if (s) { int i; for (i = 0; i < asdl_seq_LEN(s); i++) { if (!set_context(c, (expr_ty)asdl_seq_GET(s, i), ctx, n)) return 0; } } return 1; } static operator_ty ast_for_augassign(struct compiling *c, const node *n) { REQ(n, augassign); n = CHILD(n, 0); switch (STR(n)[0]) { case '+': return Add; case '-': return Sub; case '/': if (STR(n)[1] == '/') return FloorDiv; else return Div; case '%': return Mod; case '<': return LShift; case '>': return RShift; case '&': return BitAnd; case '^': return BitXor; case '|': return BitOr; case '*': if (STR(n)[1] == '*') return Pow; else return Mult; case '@': return MatMult; default: PyErr_Format(PyExc_SystemError, "invalid augassign: %s", STR(n)); return (operator_ty)0; } } static cmpop_ty ast_for_comp_op(struct compiling *c, const node *n) { /* comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is' |'is' 'not' */ REQ(n, comp_op); if (NCH(n) == 1) { n = CHILD(n, 0); switch (TYPE(n)) { case LESS: return Lt; case GREATER: return Gt; case EQEQUAL: /* == */ return Eq; case LESSEQUAL: return LtE; case GREATEREQUAL: return GtE; case NOTEQUAL: return NotEq; case NAME: if (strcmp(STR(n), "in") == 0) return In; if (strcmp(STR(n), "is") == 0) return Is; /* fall through */ default: PyErr_Format(PyExc_SystemError, "invalid comp_op: %s", STR(n)); return (cmpop_ty)0; } } else if (NCH(n) == 2) { /* handle "not in" and "is not" */ switch (TYPE(CHILD(n, 0))) { case NAME: if (strcmp(STR(CHILD(n, 1)), "in") == 0) return NotIn; if (strcmp(STR(CHILD(n, 0)), "is") == 0) return IsNot; /* fall through */ default: PyErr_Format(PyExc_SystemError, "invalid comp_op: %s %s", STR(CHILD(n, 0)), STR(CHILD(n, 1))); return (cmpop_ty)0; } } PyErr_Format(PyExc_SystemError, "invalid comp_op: has %d children", NCH(n)); return (cmpop_ty)0; } static asdl_seq * seq_for_testlist(struct compiling *c, const node *n) { /* testlist: test (',' test)* [','] testlist_star_expr: test|star_expr (',' test|star_expr)* [','] */ asdl_seq *seq; expr_ty expression; int i; assert(TYPE(n) == testlist || TYPE(n) == testlist_star_expr || TYPE(n) == testlist_comp); seq = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!seq) return NULL; for (i = 0; i < NCH(n); i += 2) { const node *ch = CHILD(n, i); assert(TYPE(ch) == test || TYPE(ch) == test_nocond || TYPE(ch) == star_expr); expression = ast_for_expr(c, ch); if (!expression) return NULL; assert(i / 2 < seq->size); asdl_seq_SET(seq, i / 2, expression); } return seq; } static arg_ty ast_for_arg(struct compiling *c, const node *n) { identifier name; expr_ty annotation = NULL; node *ch; arg_ty ret; assert(TYPE(n) == tfpdef || TYPE(n) == vfpdef); ch = CHILD(n, 0); name = NEW_IDENTIFIER(ch); if (!name) return NULL; if (forbidden_name(c, name, ch, 0)) return NULL; if (NCH(n) == 3 && TYPE(CHILD(n, 1)) == COLON) { annotation = ast_for_expr(c, CHILD(n, 2)); if (!annotation) return NULL; } ret = arg(name, annotation, LINENO(n), n->n_col_offset, c->c_arena); if (!ret) return NULL; return ret; } /* returns -1 if failed to handle keyword only arguments returns new position to keep processing if successful (',' tfpdef ['=' test])* ^^^ start pointing here */ static int handle_keywordonly_args(struct compiling *c, const node *n, int start, asdl_seq *kwonlyargs, asdl_seq *kwdefaults) { PyObject *argname; node *ch; expr_ty expression, annotation; arg_ty arg; int i = start; int j = 0; /* index for kwdefaults and kwonlyargs */ if (kwonlyargs == NULL) { ast_error(c, CHILD(n, start), "named arguments must follow bare *"); return -1; } assert(kwdefaults != NULL); while (i < NCH(n)) { ch = CHILD(n, i); switch (TYPE(ch)) { case vfpdef: case tfpdef: if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) { expression = ast_for_expr(c, CHILD(n, i + 2)); if (!expression) goto error; asdl_seq_SET(kwdefaults, j, expression); i += 2; /* '=' and test */ } else { /* setting NULL if no default value exists */ asdl_seq_SET(kwdefaults, j, NULL); } if (NCH(ch) == 3) { /* ch is NAME ':' test */ annotation = ast_for_expr(c, CHILD(ch, 2)); if (!annotation) goto error; } else { annotation = NULL; } ch = CHILD(ch, 0); argname = NEW_IDENTIFIER(ch); if (!argname) goto error; if (forbidden_name(c, argname, ch, 0)) goto error; arg = arg(argname, annotation, LINENO(ch), ch->n_col_offset, c->c_arena); if (!arg) goto error; asdl_seq_SET(kwonlyargs, j++, arg); i += 2; /* the name and the comma */ break; case DOUBLESTAR: return i; default: ast_error(c, ch, "unexpected node"); goto error; } } return i; error: return -1; } /* Create AST for argument list. */ static arguments_ty ast_for_arguments(struct compiling *c, const node *n) { /* This function handles both typedargslist (function definition) and varargslist (lambda definition). parameters: '(' [typedargslist] ')' typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [ '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] | '**' tfpdef [',']]] | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] | '**' tfpdef [',']) tfpdef: NAME [':' test] varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [ '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] | '**' vfpdef [',']]] | '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]] | '**' vfpdef [','] ) vfpdef: NAME */ int i, j, k, nposargs = 0, nkwonlyargs = 0; int nposdefaults = 0, found_default = 0; asdl_seq *posargs, *posdefaults, *kwonlyargs, *kwdefaults; arg_ty vararg = NULL, kwarg = NULL; arg_ty arg; node *ch; if (TYPE(n) == parameters) { if (NCH(n) == 2) /* () as argument list */ return arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena); n = CHILD(n, 1); } assert(TYPE(n) == typedargslist || TYPE(n) == varargslist); /* First count the number of positional args & defaults. The variable i is the loop index for this for loop and the next. The next loop picks up where the first leaves off. */ for (i = 0; i < NCH(n); i++) { ch = CHILD(n, i); if (TYPE(ch) == STAR) { /* skip star */ i++; if (i < NCH(n) && /* skip argument following star */ (TYPE(CHILD(n, i)) == tfpdef || TYPE(CHILD(n, i)) == vfpdef)) { i++; } break; } if (TYPE(ch) == DOUBLESTAR) break; if (TYPE(ch) == vfpdef || TYPE(ch) == tfpdef) nposargs++; if (TYPE(ch) == EQUAL) nposdefaults++; } /* count the number of keyword only args & defaults for keyword only args */ for ( ; i < NCH(n); ++i) { ch = CHILD(n, i); if (TYPE(ch) == DOUBLESTAR) break; if (TYPE(ch) == tfpdef || TYPE(ch) == vfpdef) nkwonlyargs++; } posargs = (nposargs ? _Py_asdl_seq_new(nposargs, c->c_arena) : NULL); if (!posargs && nposargs) return NULL; kwonlyargs = (nkwonlyargs ? _Py_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL); if (!kwonlyargs && nkwonlyargs) return NULL; posdefaults = (nposdefaults ? _Py_asdl_seq_new(nposdefaults, c->c_arena) : NULL); if (!posdefaults && nposdefaults) return NULL; /* The length of kwonlyargs and kwdefaults are same since we set NULL as default for keyword only argument w/o default - we have sequence data structure, but no dictionary */ kwdefaults = (nkwonlyargs ? _Py_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL); if (!kwdefaults && nkwonlyargs) return NULL; if (nposargs + nkwonlyargs > 255) { ast_error(c, n, "more than 255 arguments"); return NULL; } /* tfpdef: NAME [':' test] vfpdef: NAME */ i = 0; j = 0; /* index for defaults */ k = 0; /* index for args */ while (i < NCH(n)) { ch = CHILD(n, i); switch (TYPE(ch)) { case tfpdef: case vfpdef: /* XXX Need to worry about checking if TYPE(CHILD(n, i+1)) is anything other than EQUAL or a comma? */ /* XXX Should NCH(n) check be made a separate check? */ if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) { expr_ty expression = ast_for_expr(c, CHILD(n, i + 2)); if (!expression) return NULL; assert(posdefaults != NULL); asdl_seq_SET(posdefaults, j++, expression); i += 2; found_default = 1; } else if (found_default) { ast_error(c, n, "non-default argument follows default argument"); return NULL; } arg = ast_for_arg(c, ch); if (!arg) return NULL; asdl_seq_SET(posargs, k++, arg); i += 2; /* the name and the comma */ break; case STAR: if (i+1 >= NCH(n) || (i+2 == NCH(n) && TYPE(CHILD(n, i+1)) == COMMA)) { ast_error(c, CHILD(n, i), "named arguments must follow bare *"); return NULL; } ch = CHILD(n, i+1); /* tfpdef or COMMA */ if (TYPE(ch) == COMMA) { int res = 0; i += 2; /* now follows keyword only arguments */ res = handle_keywordonly_args(c, n, i, kwonlyargs, kwdefaults); if (res == -1) return NULL; i = res; /* res has new position to process */ } else { vararg = ast_for_arg(c, ch); if (!vararg) return NULL; i += 3; if (i < NCH(n) && (TYPE(CHILD(n, i)) == tfpdef || TYPE(CHILD(n, i)) == vfpdef)) { int res = 0; res = handle_keywordonly_args(c, n, i, kwonlyargs, kwdefaults); if (res == -1) return NULL; i = res; /* res has new position to process */ } } break; case DOUBLESTAR: ch = CHILD(n, i+1); /* tfpdef */ assert(TYPE(ch) == tfpdef || TYPE(ch) == vfpdef); kwarg = ast_for_arg(c, ch); if (!kwarg) return NULL; i += 3; break; default: PyErr_Format(PyExc_SystemError, "unexpected node in varargslist: %d @ %d", TYPE(ch), i); return NULL; } } return arguments(posargs, vararg, kwonlyargs, kwdefaults, kwarg, posdefaults, c->c_arena); } static expr_ty ast_for_dotted_name(struct compiling *c, const node *n) { expr_ty e; identifier id; int lineno, col_offset; int i; REQ(n, dotted_name); lineno = LINENO(n); col_offset = n->n_col_offset; id = NEW_IDENTIFIER(CHILD(n, 0)); if (!id) return NULL; e = Name(id, Load, lineno, col_offset, c->c_arena); if (!e) return NULL; for (i = 2; i < NCH(n); i+=2) { id = NEW_IDENTIFIER(CHILD(n, i)); if (!id) return NULL; e = Attribute(e, id, Load, lineno, col_offset, c->c_arena); if (!e) return NULL; } return e; } static expr_ty ast_for_decorator(struct compiling *c, const node *n) { /* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */ expr_ty d = NULL; expr_ty name_expr; REQ(n, decorator); REQ(CHILD(n, 0), AT); REQ(RCHILD(n, -1), NEWLINE); name_expr = ast_for_dotted_name(c, CHILD(n, 1)); if (!name_expr) return NULL; if (NCH(n) == 3) { /* No arguments */ d = name_expr; name_expr = NULL; } else if (NCH(n) == 5) { /* Call with no arguments */ d = Call(name_expr, NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena); if (!d) return NULL; name_expr = NULL; } else { d = ast_for_call(c, CHILD(n, 3), name_expr); if (!d) return NULL; name_expr = NULL; } return d; } static asdl_seq* ast_for_decorators(struct compiling *c, const node *n) { asdl_seq* decorator_seq; expr_ty d; int i; REQ(n, decorators); decorator_seq = _Py_asdl_seq_new(NCH(n), c->c_arena); if (!decorator_seq) return NULL; for (i = 0; i < NCH(n); i++) { d = ast_for_decorator(c, CHILD(n, i)); if (!d) return NULL; asdl_seq_SET(decorator_seq, i, d); } return decorator_seq; } static stmt_ty ast_for_funcdef_impl(struct compiling *c, const node *n, asdl_seq *decorator_seq, int is_async) { /* funcdef: 'def' NAME parameters ['->' test] ':' suite */ identifier name; arguments_ty args; asdl_seq *body; expr_ty returns = NULL; int name_i = 1; REQ(n, funcdef); name = NEW_IDENTIFIER(CHILD(n, name_i)); if (!name) return NULL; if (forbidden_name(c, name, CHILD(n, name_i), 0)) return NULL; args = ast_for_arguments(c, CHILD(n, name_i + 1)); if (!args) return NULL; if (TYPE(CHILD(n, name_i+2)) == RARROW) { returns = ast_for_expr(c, CHILD(n, name_i + 3)); if (!returns) return NULL; name_i += 2; } body = ast_for_suite(c, CHILD(n, name_i + 3)); if (!body) return NULL; if (is_async) return AsyncFunctionDef(name, args, body, decorator_seq, returns, LINENO(n), n->n_col_offset, c->c_arena); else return FunctionDef(name, args, body, decorator_seq, returns, LINENO(n), n->n_col_offset, c->c_arena); } static stmt_ty ast_for_async_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq) { /* async_funcdef: ASYNC funcdef */ REQ(n, async_funcdef); REQ(CHILD(n, 0), ASYNC); REQ(CHILD(n, 1), funcdef); return ast_for_funcdef_impl(c, CHILD(n, 1), decorator_seq, 1 /* is_async */); } static stmt_ty ast_for_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq) { /* funcdef: 'def' NAME parameters ['->' test] ':' suite */ return ast_for_funcdef_impl(c, n, decorator_seq, 0 /* is_async */); } static stmt_ty ast_for_async_stmt(struct compiling *c, const node *n) { /* async_stmt: ASYNC (funcdef | with_stmt | for_stmt) */ REQ(n, async_stmt); REQ(CHILD(n, 0), ASYNC); switch (TYPE(CHILD(n, 1))) { case funcdef: return ast_for_funcdef_impl(c, CHILD(n, 1), NULL, 1 /* is_async */); case with_stmt: return ast_for_with_stmt(c, CHILD(n, 1), 1 /* is_async */); case for_stmt: return ast_for_for_stmt(c, CHILD(n, 1), 1 /* is_async */); default: PyErr_Format(PyExc_SystemError, "invalid async stament: %s", STR(CHILD(n, 1))); return NULL; } } static stmt_ty ast_for_decorated(struct compiling *c, const node *n) { /* decorated: decorators (classdef | funcdef | async_funcdef) */ stmt_ty thing = NULL; asdl_seq *decorator_seq = NULL; REQ(n, decorated); decorator_seq = ast_for_decorators(c, CHILD(n, 0)); if (!decorator_seq) return NULL; assert(TYPE(CHILD(n, 1)) == funcdef || TYPE(CHILD(n, 1)) == async_funcdef || TYPE(CHILD(n, 1)) == classdef); if (TYPE(CHILD(n, 1)) == funcdef) { thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq); } else if (TYPE(CHILD(n, 1)) == classdef) { thing = ast_for_classdef(c, CHILD(n, 1), decorator_seq); } else if (TYPE(CHILD(n, 1)) == async_funcdef) { thing = ast_for_async_funcdef(c, CHILD(n, 1), decorator_seq); } /* we count the decorators in when talking about the class' or * function's line number */ if (thing) { thing->lineno = LINENO(n); thing->col_offset = n->n_col_offset; } return thing; } static expr_ty ast_for_lambdef(struct compiling *c, const node *n) { /* lambdef: 'lambda' [varargslist] ':' test lambdef_nocond: 'lambda' [varargslist] ':' test_nocond */ arguments_ty args; expr_ty expression; if (NCH(n) == 3) { args = arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena); if (!args) return NULL; expression = ast_for_expr(c, CHILD(n, 2)); if (!expression) return NULL; } else { args = ast_for_arguments(c, CHILD(n, 1)); if (!args) return NULL; expression = ast_for_expr(c, CHILD(n, 3)); if (!expression) return NULL; } return Lambda(args, expression, LINENO(n), n->n_col_offset, c->c_arena); } static expr_ty ast_for_ifexpr(struct compiling *c, const node *n) { /* test: or_test 'if' or_test 'else' test */ expr_ty expression, body, orelse; assert(NCH(n) == 5); body = ast_for_expr(c, CHILD(n, 0)); if (!body) return NULL; expression = ast_for_expr(c, CHILD(n, 2)); if (!expression) return NULL; orelse = ast_for_expr(c, CHILD(n, 4)); if (!orelse) return NULL; return IfExp(expression, body, orelse, LINENO(n), n->n_col_offset, c->c_arena); } /* Count the number of 'for' loops in a comprehension. Helper for ast_for_comprehension(). */ static int count_comp_fors(struct compiling *c, const node *n) { int n_fors = 0; int is_async; count_comp_for: is_async = 0; n_fors++; REQ(n, comp_for); if (TYPE(CHILD(n, 0)) == ASYNC) { is_async = 1; } if (NCH(n) == (5 + is_async)) { n = CHILD(n, 4 + is_async); } else { return n_fors; } count_comp_iter: REQ(n, comp_iter); n = CHILD(n, 0); if (TYPE(n) == comp_for) goto count_comp_for; else if (TYPE(n) == comp_if) { if (NCH(n) == 3) { n = CHILD(n, 2); goto count_comp_iter; } else return n_fors; } /* Should never be reached */ PyErr_SetString(PyExc_SystemError, "logic error in count_comp_fors"); return -1; } /* Count the number of 'if' statements in a comprehension. Helper for ast_for_comprehension(). */ static int count_comp_ifs(struct compiling *c, const node *n) { int n_ifs = 0; while (1) { REQ(n, comp_iter); if (TYPE(CHILD(n, 0)) == comp_for) return n_ifs; n = CHILD(n, 0); REQ(n, comp_if); n_ifs++; if (NCH(n) == 2) return n_ifs; n = CHILD(n, 2); } } static asdl_seq * ast_for_comprehension(struct compiling *c, const node *n) { int i, n_fors; asdl_seq *comps; n_fors = count_comp_fors(c, n); if (n_fors == -1) return NULL; comps = _Py_asdl_seq_new(n_fors, c->c_arena); if (!comps) return NULL; for (i = 0; i < n_fors; i++) { comprehension_ty comp; asdl_seq *t; expr_ty expression, first; node *for_ch; int is_async = 0; REQ(n, comp_for); if (TYPE(CHILD(n, 0)) == ASYNC) { is_async = 1; } for_ch = CHILD(n, 1 + is_async); t = ast_for_exprlist(c, for_ch, Store); if (!t) return NULL; expression = ast_for_expr(c, CHILD(n, 3 + is_async)); if (!expression) return NULL; /* Check the # of children rather than the length of t, since (x for x, in ...) has 1 element in t, but still requires a Tuple. */ first = (expr_ty)asdl_seq_GET(t, 0); if (NCH(for_ch) == 1) comp = comprehension(first, expression, NULL, is_async, c->c_arena); else comp = comprehension(Tuple(t, Store, first->lineno, first->col_offset, c->c_arena), expression, NULL, is_async, c->c_arena); if (!comp) return NULL; if (NCH(n) == (5 + is_async)) { int j, n_ifs; asdl_seq *ifs; n = CHILD(n, 4 + is_async); n_ifs = count_comp_ifs(c, n); if (n_ifs == -1) return NULL; ifs = _Py_asdl_seq_new(n_ifs, c->c_arena); if (!ifs) return NULL; for (j = 0; j < n_ifs; j++) { REQ(n, comp_iter); n = CHILD(n, 0); REQ(n, comp_if); expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; asdl_seq_SET(ifs, j, expression); if (NCH(n) == 3) n = CHILD(n, 2); } /* on exit, must guarantee that n is a comp_for */ if (TYPE(n) == comp_iter) n = CHILD(n, 0); comp->ifs = ifs; } asdl_seq_SET(comps, i, comp); } return comps; } static expr_ty ast_for_itercomp(struct compiling *c, const node *n, int type) { /* testlist_comp: (test|star_expr) * ( comp_for | (',' (test|star_expr))* [','] ) */ expr_ty elt; asdl_seq *comps; node *ch; assert(NCH(n) > 1); ch = CHILD(n, 0); elt = ast_for_expr(c, ch); if (!elt) return NULL; if (elt->kind == Starred_kind) { ast_error(c, ch, "iterable unpacking cannot be used in comprehension"); return NULL; } comps = ast_for_comprehension(c, CHILD(n, 1)); if (!comps) return NULL; if (type == COMP_GENEXP) return GeneratorExp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena); else if (type == COMP_LISTCOMP) return ListComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena); else if (type == COMP_SETCOMP) return SetComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena); else /* Should never happen */ return NULL; } /* Fills in the key, value pair corresponding to the dict element. In case * of an unpacking, key is NULL. *i is advanced by the number of ast * elements. Iff successful, nonzero is returned. */ static int ast_for_dictelement(struct compiling *c, const node *n, int *i, expr_ty *key, expr_ty *value) { expr_ty expression; if (TYPE(CHILD(n, *i)) == DOUBLESTAR) { assert(NCH(n) - *i >= 2); expression = ast_for_expr(c, CHILD(n, *i + 1)); if (!expression) return 0; *key = NULL; *value = expression; *i += 2; } else { assert(NCH(n) - *i >= 3); expression = ast_for_expr(c, CHILD(n, *i)); if (!expression) return 0; *key = expression; REQ(CHILD(n, *i + 1), COLON); expression = ast_for_expr(c, CHILD(n, *i + 2)); if (!expression) return 0; *value = expression; *i += 3; } return 1; } static expr_ty ast_for_dictcomp(struct compiling *c, const node *n) { expr_ty key, value; asdl_seq *comps; int i = 0; if (!ast_for_dictelement(c, n, &i, &key, &value)) return NULL; assert(key); assert(NCH(n) - i >= 1); comps = ast_for_comprehension(c, CHILD(n, i)); if (!comps) return NULL; return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena); } static expr_ty ast_for_dictdisplay(struct compiling *c, const node *n) { int i; int j; int size; asdl_seq *keys, *values; size = (NCH(n) + 1) / 3; /* +1 in case no trailing comma */ keys = _Py_asdl_seq_new(size, c->c_arena); if (!keys) return NULL; values = _Py_asdl_seq_new(size, c->c_arena); if (!values) return NULL; j = 0; for (i = 0; i < NCH(n); i++) { expr_ty key, value; if (!ast_for_dictelement(c, n, &i, &key, &value)) return NULL; asdl_seq_SET(keys, j, key); asdl_seq_SET(values, j, value); j++; } keys->size = j; values->size = j; return Dict(keys, values, LINENO(n), n->n_col_offset, c->c_arena); } static expr_ty ast_for_genexp(struct compiling *c, const node *n) { assert(TYPE(n) == (testlist_comp) || TYPE(n) == (argument)); return ast_for_itercomp(c, n, COMP_GENEXP); } static expr_ty ast_for_listcomp(struct compiling *c, const node *n) { assert(TYPE(n) == (testlist_comp)); return ast_for_itercomp(c, n, COMP_LISTCOMP); } static expr_ty ast_for_setcomp(struct compiling *c, const node *n) { assert(TYPE(n) == (dictorsetmaker)); return ast_for_itercomp(c, n, COMP_SETCOMP); } static expr_ty ast_for_setdisplay(struct compiling *c, const node *n) { int i; int size; asdl_seq *elts; assert(TYPE(n) == (dictorsetmaker)); size = (NCH(n) + 1) / 2; /* +1 in case no trailing comma */ elts = _Py_asdl_seq_new(size, c->c_arena); if (!elts) return NULL; for (i = 0; i < NCH(n); i += 2) { expr_ty expression; expression = ast_for_expr(c, CHILD(n, i)); if (!expression) return NULL; asdl_seq_SET(elts, i / 2, expression); } return Set(elts, LINENO(n), n->n_col_offset, c->c_arena); } static expr_ty ast_for_atom(struct compiling *c, const node *n) { /* atom: '(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']' | '{' [dictmaker|testlist_comp] '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False' */ node *ch = CHILD(n, 0); switch (TYPE(ch)) { case NAME: { PyObject *name; const char *s = STR(ch); size_t len = strlen(s); if (len >= 4 && len <= 5) { if (!strcmp(s, "None")) return NameConstant(Py_None, LINENO(n), n->n_col_offset, c->c_arena); if (!strcmp(s, "True")) return NameConstant(Py_True, LINENO(n), n->n_col_offset, c->c_arena); if (!strcmp(s, "False")) return NameConstant(Py_False, LINENO(n), n->n_col_offset, c->c_arena); } name = new_identifier(s, c); if (!name) return NULL; /* All names start in Load context, but may later be changed. */ return Name(name, Load, LINENO(n), n->n_col_offset, c->c_arena); } case STRING: { expr_ty str = parsestrplus(c, n); if (!str) { const char *errtype = NULL; if (PyErr_ExceptionMatches(PyExc_UnicodeError)) errtype = "unicode error"; else if (PyErr_ExceptionMatches(PyExc_ValueError)) errtype = "value error"; if (errtype) { char buf[128]; const char *s = NULL; PyObject *type, *value, *tback, *errstr; PyErr_Fetch(&type, &value, &tback); errstr = PyObject_Str(value); if (errstr) s = PyUnicode_AsUTF8(errstr); if (s) { PyOS_snprintf(buf, sizeof(buf), "(%s) %s", errtype, s); } else { PyErr_Clear(); PyOS_snprintf(buf, sizeof(buf), "(%s) unknown error", errtype); } Py_XDECREF(errstr); ast_error(c, n, buf); Py_DECREF(type); Py_XDECREF(value); Py_XDECREF(tback); } return NULL; } return str; } case NUMBER: { PyObject *pynum = parsenumber(c, STR(ch)); if (!pynum) return NULL; if (PyArena_AddPyObject(c->c_arena, pynum) < 0) { Py_DECREF(pynum); return NULL; } return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena); } case ELLIPSIS: /* Ellipsis */ return Ellipsis(LINENO(n), n->n_col_offset, c->c_arena); case LPAR: /* some parenthesized expressions */ ch = CHILD(n, 1); if (TYPE(ch) == RPAR) return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); if (TYPE(ch) == yield_expr) return ast_for_expr(c, ch); /* testlist_comp: test ( comp_for | (',' test)* [','] ) */ if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == comp_for)) return ast_for_genexp(c, ch); return ast_for_testlist(c, ch); case LSQB: /* list (or list comprehension) */ ch = CHILD(n, 1); if (TYPE(ch) == RSQB) return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena); REQ(ch, testlist_comp); if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) { asdl_seq *elts = seq_for_testlist(c, ch); if (!elts) return NULL; return List(elts, Load, LINENO(n), n->n_col_offset, c->c_arena); } else return ast_for_listcomp(c, ch); case LBRACE: { /* dictorsetmaker: ( ((test ':' test | '**' test) * (comp_for | (',' (test ':' test | '**' test))* [','])) | * ((test | '*' test) * (comp_for | (',' (test | '*' test))* [','])) ) */ expr_ty res; ch = CHILD(n, 1); if (TYPE(ch) == RBRACE) { /* It's an empty dict. */ return Dict(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena); } else { int is_dict = (TYPE(CHILD(ch, 0)) == DOUBLESTAR); if (NCH(ch) == 1 || (NCH(ch) > 1 && TYPE(CHILD(ch, 1)) == COMMA)) { /* It's a set display. */ res = ast_for_setdisplay(c, ch); } else if (NCH(ch) > 1 && TYPE(CHILD(ch, 1)) == comp_for) { /* It's a set comprehension. */ res = ast_for_setcomp(c, ch); } else if (NCH(ch) > 3 - is_dict && TYPE(CHILD(ch, 3 - is_dict)) == comp_for) { /* It's a dictionary comprehension. */ if (is_dict) { ast_error(c, n, "dict unpacking cannot be used in " "dict comprehension"); return NULL; } res = ast_for_dictcomp(c, ch); } else { /* It's a dictionary display. */ res = ast_for_dictdisplay(c, ch); } if (res) { res->lineno = LINENO(n); res->col_offset = n->n_col_offset; } return res; } } default: PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch)); return NULL; } } static slice_ty ast_for_slice(struct compiling *c, const node *n) { node *ch; expr_ty lower = NULL, upper = NULL, step = NULL; REQ(n, subscript); /* subscript: test | [test] ':' [test] [sliceop] sliceop: ':' [test] */ ch = CHILD(n, 0); if (NCH(n) == 1 && TYPE(ch) == test) { /* 'step' variable hold no significance in terms of being used over other vars */ step = ast_for_expr(c, ch); if (!step) return NULL; return Index(step, c->c_arena); } if (TYPE(ch) == test) { lower = ast_for_expr(c, ch); if (!lower) return NULL; } /* If there's an upper bound it's in the second or third position. */ if (TYPE(ch) == COLON) { if (NCH(n) > 1) { node *n2 = CHILD(n, 1); if (TYPE(n2) == test) { upper = ast_for_expr(c, n2); if (!upper) return NULL; } } } else if (NCH(n) > 2) { node *n2 = CHILD(n, 2); if (TYPE(n2) == test) { upper = ast_for_expr(c, n2); if (!upper) return NULL; } } ch = CHILD(n, NCH(n) - 1); if (TYPE(ch) == sliceop) { if (NCH(ch) != 1) { ch = CHILD(ch, 1); if (TYPE(ch) == test) { step = ast_for_expr(c, ch); if (!step) return NULL; } } } return Slice(lower, upper, step, c->c_arena); } static expr_ty ast_for_binop(struct compiling *c, const node *n) { /* Must account for a sequence of expressions. How should A op B op C by represented? BinOp(BinOp(A, op, B), op, C). */ int i, nops; expr_ty expr1, expr2, result; operator_ty newoperator; expr1 = ast_for_expr(c, CHILD(n, 0)); if (!expr1) return NULL; expr2 = ast_for_expr(c, CHILD(n, 2)); if (!expr2) return NULL; newoperator = get_operator(CHILD(n, 1)); if (!newoperator) return NULL; result = BinOp(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, c->c_arena); if (!result) return NULL; nops = (NCH(n) - 1) / 2; for (i = 1; i < nops; i++) { expr_ty tmp_result, tmp; const node* next_oper = CHILD(n, i * 2 + 1); newoperator = get_operator(next_oper); if (!newoperator) return NULL; tmp = ast_for_expr(c, CHILD(n, i * 2 + 2)); if (!tmp) return NULL; tmp_result = BinOp(result, newoperator, tmp, LINENO(next_oper), next_oper->n_col_offset, c->c_arena); if (!tmp_result) return NULL; result = tmp_result; } return result; } static expr_ty ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr) { /* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME subscriptlist: subscript (',' subscript)* [','] subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] */ REQ(n, trailer); if (TYPE(CHILD(n, 0)) == LPAR) { if (NCH(n) == 2) return Call(left_expr, NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena); else return ast_for_call(c, CHILD(n, 1), left_expr); } else if (TYPE(CHILD(n, 0)) == DOT) { PyObject *attr_id = NEW_IDENTIFIER(CHILD(n, 1)); if (!attr_id) return NULL; return Attribute(left_expr, attr_id, Load, LINENO(n), n->n_col_offset, c->c_arena); } else { REQ(CHILD(n, 0), LSQB); REQ(CHILD(n, 2), RSQB); n = CHILD(n, 1); if (NCH(n) == 1) { slice_ty slc = ast_for_slice(c, CHILD(n, 0)); if (!slc) return NULL; return Subscript(left_expr, slc, Load, LINENO(n), n->n_col_offset, c->c_arena); } else { /* The grammar is ambiguous here. The ambiguity is resolved by treating the sequence as a tuple literal if there are no slice features. */ int j; slice_ty slc; expr_ty e; int simple = 1; asdl_seq *slices, *elts; slices = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!slices) return NULL; for (j = 0; j < NCH(n); j += 2) { slc = ast_for_slice(c, CHILD(n, j)); if (!slc) return NULL; if (slc->kind != Index_kind) simple = 0; asdl_seq_SET(slices, j / 2, slc); } if (!simple) { return Subscript(left_expr, ExtSlice(slices, c->c_arena), Load, LINENO(n), n->n_col_offset, c->c_arena); } /* extract Index values and put them in a Tuple */ elts = _Py_asdl_seq_new(asdl_seq_LEN(slices), c->c_arena); if (!elts) return NULL; for (j = 0; j < asdl_seq_LEN(slices); ++j) { slc = (slice_ty)asdl_seq_GET(slices, j); assert(slc->kind == Index_kind && slc->v.Index.value); asdl_seq_SET(elts, j, slc->v.Index.value); } e = Tuple(elts, Load, LINENO(n), n->n_col_offset, c->c_arena); if (!e) return NULL; return Subscript(left_expr, Index(e, c->c_arena), Load, LINENO(n), n->n_col_offset, c->c_arena); } } } static expr_ty ast_for_factor(struct compiling *c, const node *n) { expr_ty expression; expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; switch (TYPE(CHILD(n, 0))) { case PLUS: return UnaryOp(UAdd, expression, LINENO(n), n->n_col_offset, c->c_arena); case MINUS: return UnaryOp(USub, expression, LINENO(n), n->n_col_offset, c->c_arena); case TILDE: return UnaryOp(Invert, expression, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "unhandled factor: %d", TYPE(CHILD(n, 0))); return NULL; } static expr_ty ast_for_atom_expr(struct compiling *c, const node *n) { int i, nch, start = 0; expr_ty e, tmp; REQ(n, atom_expr); nch = NCH(n); if (TYPE(CHILD(n, 0)) == AWAIT) { start = 1; assert(nch > 1); } e = ast_for_atom(c, CHILD(n, start)); if (!e) return NULL; if (nch == 1) return e; if (start && nch == 2) { return Await(e, LINENO(n), n->n_col_offset, c->c_arena); } for (i = start + 1; i < nch; i++) { node *ch = CHILD(n, i); if (TYPE(ch) != trailer) break; tmp = ast_for_trailer(c, ch, e); if (!tmp) return NULL; tmp->lineno = e->lineno; tmp->col_offset = e->col_offset; e = tmp; } if (start) { /* there was an AWAIT */ return Await(e, LINENO(n), n->n_col_offset, c->c_arena); } else { return e; } } static expr_ty ast_for_power(struct compiling *c, const node *n) { /* power: atom trailer* ('**' factor)* */ expr_ty e; REQ(n, power); e = ast_for_atom_expr(c, CHILD(n, 0)); if (!e) return NULL; if (NCH(n) == 1) return e; if (TYPE(CHILD(n, NCH(n) - 1)) == factor) { expr_ty f = ast_for_expr(c, CHILD(n, NCH(n) - 1)); if (!f) return NULL; e = BinOp(e, Pow, f, LINENO(n), n->n_col_offset, c->c_arena); } return e; } static expr_ty ast_for_starred(struct compiling *c, const node *n) { expr_ty tmp; REQ(n, star_expr); tmp = ast_for_expr(c, CHILD(n, 1)); if (!tmp) return NULL; /* The Load context is changed later. */ return Starred(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena); } /* Do not name a variable 'expr'! Will cause a compile error. */ static expr_ty ast_for_expr(struct compiling *c, const node *n) { /* handle the full range of simple expressions test: or_test ['if' or_test 'else' test] | lambdef test_nocond: or_test | lambdef_nocond or_test: and_test ('or' and_test)* and_test: not_test ('and' not_test)* not_test: 'not' not_test | comparison comparison: expr (comp_op expr)* expr: xor_expr ('|' xor_expr)* xor_expr: and_expr ('^' and_expr)* and_expr: shift_expr ('&' shift_expr)* shift_expr: arith_expr (('<<'|'>>') arith_expr)* arith_expr: term (('+'|'-') term)* term: factor (('*'|'@'|'/'|'%'|'//') factor)* factor: ('+'|'-'|'~') factor | power power: atom_expr ['**' factor] atom_expr: [AWAIT] atom trailer* yield_expr: 'yield' [yield_arg] */ asdl_seq *seq; int i; loop: switch (TYPE(n)) { case test: case test_nocond: if (TYPE(CHILD(n, 0)) == lambdef || TYPE(CHILD(n, 0)) == lambdef_nocond) return ast_for_lambdef(c, CHILD(n, 0)); else if (NCH(n) > 1) return ast_for_ifexpr(c, n); /* Fallthrough */ case or_test: case and_test: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } seq = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!seq) return NULL; for (i = 0; i < NCH(n); i += 2) { expr_ty e = ast_for_expr(c, CHILD(n, i)); if (!e) return NULL; asdl_seq_SET(seq, i / 2, e); } if (!strcmp(STR(CHILD(n, 1)), "and")) return BoolOp(And, seq, LINENO(n), n->n_col_offset, c->c_arena); assert(!strcmp(STR(CHILD(n, 1)), "or")); return BoolOp(Or, seq, LINENO(n), n->n_col_offset, c->c_arena); case not_test: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } else { expr_ty expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; return UnaryOp(Not, expression, LINENO(n), n->n_col_offset, c->c_arena); } case comparison: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } else { expr_ty expression; asdl_int_seq *ops; asdl_seq *cmps; ops = _Py_asdl_int_seq_new(NCH(n) / 2, c->c_arena); if (!ops) return NULL; cmps = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena); if (!cmps) { return NULL; } for (i = 1; i < NCH(n); i += 2) { cmpop_ty newoperator; newoperator = ast_for_comp_op(c, CHILD(n, i)); if (!newoperator) { return NULL; } expression = ast_for_expr(c, CHILD(n, i + 1)); if (!expression) { return NULL; } asdl_seq_SET(ops, i / 2, newoperator); asdl_seq_SET(cmps, i / 2, expression); } expression = ast_for_expr(c, CHILD(n, 0)); if (!expression) { return NULL; } return Compare(expression, ops, cmps, LINENO(n), n->n_col_offset, c->c_arena); } break; case star_expr: return ast_for_starred(c, n); /* The next five cases all handle BinOps. The main body of code is the same in each case, but the switch turned inside out to reuse the code for each type of operator. */ case expr: case xor_expr: case and_expr: case shift_expr: case arith_expr: case term: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } return ast_for_binop(c, n); case yield_expr: { node *an = NULL; node *en = NULL; int is_from = 0; expr_ty exp = NULL; if (NCH(n) > 1) an = CHILD(n, 1); /* yield_arg */ if (an) { en = CHILD(an, NCH(an) - 1); if (NCH(an) == 2) { is_from = 1; exp = ast_for_expr(c, en); } else exp = ast_for_testlist(c, en); if (!exp) return NULL; } if (is_from) return YieldFrom(exp, LINENO(n), n->n_col_offset, c->c_arena); return Yield(exp, LINENO(n), n->n_col_offset, c->c_arena); } case factor: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } return ast_for_factor(c, n); case power: return ast_for_power(c, n); default: PyErr_Format(PyExc_SystemError, "unhandled expr: %d", TYPE(n)); return NULL; } /* should never get here unless if error is set */ return NULL; } static expr_ty ast_for_call(struct compiling *c, const node *n, expr_ty func) { /* arglist: argument (',' argument)* [','] argument: ( test [comp_for] | '*' test | test '=' test | '**' test ) */ int i, nargs, nkeywords, ngens; int ndoublestars; asdl_seq *args; asdl_seq *keywords; REQ(n, arglist); nargs = 0; nkeywords = 0; ngens = 0; for (i = 0; i < NCH(n); i++) { node *ch = CHILD(n, i); if (TYPE(ch) == argument) { if (NCH(ch) == 1) nargs++; else if (TYPE(CHILD(ch, 1)) == comp_for) ngens++; else if (TYPE(CHILD(ch, 0)) == STAR) nargs++; else /* TYPE(CHILD(ch, 0)) == DOUBLESTAR or keyword argument */ nkeywords++; } } if (ngens > 1 || (ngens && (nargs || nkeywords))) { ast_error(c, n, "Generator expression must be parenthesized " "if not sole argument"); return NULL; } if (nargs + nkeywords + ngens > 255) { ast_error(c, n, "more than 255 arguments"); return NULL; } args = _Py_asdl_seq_new(nargs + ngens, c->c_arena); if (!args) return NULL; keywords = _Py_asdl_seq_new(nkeywords, c->c_arena); if (!keywords) return NULL; nargs = 0; /* positional arguments + iterable argument unpackings */ nkeywords = 0; /* keyword arguments + keyword argument unpackings */ ndoublestars = 0; /* just keyword argument unpackings */ for (i = 0; i < NCH(n); i++) { node *ch = CHILD(n, i); if (TYPE(ch) == argument) { expr_ty e; node *chch = CHILD(ch, 0); if (NCH(ch) == 1) { /* a positional argument */ if (nkeywords) { if (ndoublestars) { ast_error(c, chch, "positional argument follows " "keyword argument unpacking"); } else { ast_error(c, chch, "positional argument follows " "keyword argument"); } return NULL; } e = ast_for_expr(c, chch); if (!e) return NULL; asdl_seq_SET(args, nargs++, e); } else if (TYPE(chch) == STAR) { /* an iterable argument unpacking */ expr_ty starred; if (ndoublestars) { ast_error(c, chch, "iterable argument unpacking follows " "keyword argument unpacking"); return NULL; } e = ast_for_expr(c, CHILD(ch, 1)); if (!e) return NULL; starred = Starred(e, Load, LINENO(chch), chch->n_col_offset, c->c_arena); if (!starred) return NULL; asdl_seq_SET(args, nargs++, starred); } else if (TYPE(chch) == DOUBLESTAR) { /* a keyword argument unpacking */ keyword_ty kw; i++; e = ast_for_expr(c, CHILD(ch, 1)); if (!e) return NULL; kw = keyword(NULL, e, c->c_arena); asdl_seq_SET(keywords, nkeywords++, kw); ndoublestars++; } else if (TYPE(CHILD(ch, 1)) == comp_for) { /* the lone generator expression */ e = ast_for_genexp(c, ch); if (!e) return NULL; asdl_seq_SET(args, nargs++, e); } else { /* a keyword argument */ keyword_ty kw; identifier key, tmp; int k; /* chch is test, but must be an identifier? */ e = ast_for_expr(c, chch); if (!e) return NULL; /* f(lambda x: x[0] = 3) ends up getting parsed with * LHS test = lambda x: x[0], and RHS test = 3. * SF bug 132313 points out that complaining about a keyword * then is very confusing. */ if (e->kind == Lambda_kind) { ast_error(c, chch, "lambda cannot contain assignment"); return NULL; } else if (e->kind != Name_kind) { ast_error(c, chch, "keyword can't be an expression"); return NULL; } else if (forbidden_name(c, e->v.Name.id, ch, 1)) { return NULL; } key = e->v.Name.id; for (k = 0; k < nkeywords; k++) { tmp = ((keyword_ty)asdl_seq_GET(keywords, k))->arg; if (tmp && !PyUnicode_Compare(tmp, key)) { ast_error(c, chch, "keyword argument repeated"); return NULL; } } e = ast_for_expr(c, CHILD(ch, 2)); if (!e) return NULL; kw = keyword(key, e, c->c_arena); if (!kw) return NULL; asdl_seq_SET(keywords, nkeywords++, kw); } } } return Call(func, args, keywords, func->lineno, func->col_offset, c->c_arena); } static expr_ty ast_for_testlist(struct compiling *c, const node* n) { /* testlist_comp: test (comp_for | (',' test)* [',']) */ /* testlist: test (',' test)* [','] */ assert(NCH(n) > 0); if (TYPE(n) == testlist_comp) { if (NCH(n) > 1) assert(TYPE(CHILD(n, 1)) != comp_for); } else { assert(TYPE(n) == testlist || TYPE(n) == testlist_star_expr); } if (NCH(n) == 1) return ast_for_expr(c, CHILD(n, 0)); else { asdl_seq *tmp = seq_for_testlist(c, n); if (!tmp) return NULL; return Tuple(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena); } } static stmt_ty ast_for_expr_stmt(struct compiling *c, const node *n) { REQ(n, expr_stmt); /* expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) | ('=' (yield_expr|testlist_star_expr))*) annassign: ':' test ['=' test] testlist_star_expr: (test|star_expr) (',' test|star_expr)* [','] augassign: '+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=' test: ... here starts the operator precedence dance */ if (NCH(n) == 1) { expr_ty e = ast_for_testlist(c, CHILD(n, 0)); if (!e) return NULL; return Expr(e, LINENO(n), n->n_col_offset, c->c_arena); } else if (TYPE(CHILD(n, 1)) == augassign) { expr_ty expr1, expr2; operator_ty newoperator; node *ch = CHILD(n, 0); expr1 = ast_for_testlist(c, ch); if (!expr1) return NULL; if(!set_context(c, expr1, Store, ch)) return NULL; /* set_context checks that most expressions are not the left side. Augmented assignments can only have a name, a subscript, or an attribute on the left, though, so we have to explicitly check for those. */ switch (expr1->kind) { case Name_kind: case Attribute_kind: case Subscript_kind: break; default: ast_error(c, ch, "illegal expression for augmented assignment"); return NULL; } ch = CHILD(n, 2); if (TYPE(ch) == testlist) expr2 = ast_for_testlist(c, ch); else expr2 = ast_for_expr(c, ch); if (!expr2) return NULL; newoperator = ast_for_augassign(c, CHILD(n, 1)); if (!newoperator) return NULL; return AugAssign(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, c->c_arena); } else if (TYPE(CHILD(n, 1)) == annassign) { expr_ty expr1, expr2, expr3; node *ch = CHILD(n, 0); node *deep, *ann = CHILD(n, 1); int simple = 1; /* we keep track of parens to qualify (x) as expression not name */ deep = ch; while (NCH(deep) == 1) { deep = CHILD(deep, 0); } if (NCH(deep) > 0 && TYPE(CHILD(deep, 0)) == LPAR) { simple = 0; } expr1 = ast_for_testlist(c, ch); if (!expr1) { return NULL; } switch (expr1->kind) { case Name_kind: if (forbidden_name(c, expr1->v.Name.id, n, 0)) { return NULL; } expr1->v.Name.ctx = Store; break; case Attribute_kind: if (forbidden_name(c, expr1->v.Attribute.attr, n, 1)) { return NULL; } expr1->v.Attribute.ctx = Store; break; case Subscript_kind: expr1->v.Subscript.ctx = Store; break; case List_kind: ast_error(c, ch, "only single target (not list) can be annotated"); return NULL; case Tuple_kind: ast_error(c, ch, "only single target (not tuple) can be annotated"); return NULL; default: ast_error(c, ch, "illegal target for annotation"); return NULL; } if (expr1->kind != Name_kind) { simple = 0; } ch = CHILD(ann, 1); expr2 = ast_for_expr(c, ch); if (!expr2) { return NULL; } if (NCH(ann) == 2) { return AnnAssign(expr1, expr2, NULL, simple, LINENO(n), n->n_col_offset, c->c_arena); } else { ch = CHILD(ann, 3); expr3 = ast_for_expr(c, ch); if (!expr3) { return NULL; } return AnnAssign(expr1, expr2, expr3, simple, LINENO(n), n->n_col_offset, c->c_arena); } } else { int i; asdl_seq *targets; node *value; expr_ty expression; /* a normal assignment */ REQ(CHILD(n, 1), EQUAL); targets = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena); if (!targets) return NULL; for (i = 0; i < NCH(n) - 2; i += 2) { expr_ty e; node *ch = CHILD(n, i); if (TYPE(ch) == yield_expr) { ast_error(c, ch, "assignment to yield expression not possible"); return NULL; } e = ast_for_testlist(c, ch); if (!e) return NULL; /* set context to assign */ if (!set_context(c, e, Store, CHILD(n, i))) return NULL; asdl_seq_SET(targets, i / 2, e); } value = CHILD(n, NCH(n) - 1); if (TYPE(value) == testlist_star_expr) expression = ast_for_testlist(c, value); else expression = ast_for_expr(c, value); if (!expression) return NULL; return Assign(targets, expression, LINENO(n), n->n_col_offset, c->c_arena); } } static asdl_seq * ast_for_exprlist(struct compiling *c, const node *n, expr_context_ty context) { asdl_seq *seq; int i; expr_ty e; REQ(n, exprlist); seq = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!seq) return NULL; for (i = 0; i < NCH(n); i += 2) { e = ast_for_expr(c, CHILD(n, i)); if (!e) return NULL; asdl_seq_SET(seq, i / 2, e); if (context && !set_context(c, e, context, CHILD(n, i))) return NULL; } return seq; } static stmt_ty ast_for_del_stmt(struct compiling *c, const node *n) { asdl_seq *expr_list; /* del_stmt: 'del' exprlist */ REQ(n, del_stmt); expr_list = ast_for_exprlist(c, CHILD(n, 1), Del); if (!expr_list) return NULL; return Delete(expr_list, LINENO(n), n->n_col_offset, c->c_arena); } static stmt_ty ast_for_flow_stmt(struct compiling *c, const node *n) { /* flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt break_stmt: 'break' continue_stmt: 'continue' return_stmt: 'return' [testlist] yield_stmt: yield_expr yield_expr: 'yield' testlist | 'yield' 'from' test raise_stmt: 'raise' [test [',' test [',' test]]] */ node *ch; REQ(n, flow_stmt); ch = CHILD(n, 0); switch (TYPE(ch)) { case break_stmt: return Break(LINENO(n), n->n_col_offset, c->c_arena); case continue_stmt: return Continue(LINENO(n), n->n_col_offset, c->c_arena); case yield_stmt: { /* will reduce to yield_expr */ expr_ty exp = ast_for_expr(c, CHILD(ch, 0)); if (!exp) return NULL; return Expr(exp, LINENO(n), n->n_col_offset, c->c_arena); } case return_stmt: if (NCH(ch) == 1) return Return(NULL, LINENO(n), n->n_col_offset, c->c_arena); else { expr_ty expression = ast_for_testlist(c, CHILD(ch, 1)); if (!expression) return NULL; return Return(expression, LINENO(n), n->n_col_offset, c->c_arena); } case raise_stmt: if (NCH(ch) == 1) return Raise(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena); else if (NCH(ch) >= 2) { expr_ty cause = NULL; expr_ty expression = ast_for_expr(c, CHILD(ch, 1)); if (!expression) return NULL; if (NCH(ch) == 4) { cause = ast_for_expr(c, CHILD(ch, 3)); if (!cause) return NULL; } return Raise(expression, cause, LINENO(n), n->n_col_offset, c->c_arena); } /* fall through */ default: PyErr_Format(PyExc_SystemError, "unexpected flow_stmt: %d", TYPE(ch)); return NULL; } } static alias_ty alias_for_import_name(struct compiling *c, const node *n, int store) { /* import_as_name: NAME ['as' NAME] dotted_as_name: dotted_name ['as' NAME] dotted_name: NAME ('.' NAME)* */ identifier str, name; loop: switch (TYPE(n)) { case import_as_name: { node *name_node = CHILD(n, 0); str = NULL; name = NEW_IDENTIFIER(name_node); if (!name) return NULL; if (NCH(n) == 3) { node *str_node = CHILD(n, 2); str = NEW_IDENTIFIER(str_node); if (!str) return NULL; if (store && forbidden_name(c, str, str_node, 0)) return NULL; } else { if (forbidden_name(c, name, name_node, 0)) return NULL; } return alias(name, str, c->c_arena); } case dotted_as_name: if (NCH(n) == 1) { n = CHILD(n, 0); goto loop; } else { node *asname_node = CHILD(n, 2); alias_ty a = alias_for_import_name(c, CHILD(n, 0), 0); if (!a) return NULL; assert(!a->asname); a->asname = NEW_IDENTIFIER(asname_node); if (!a->asname) return NULL; if (forbidden_name(c, a->asname, asname_node, 0)) return NULL; return a; } break; case dotted_name: if (NCH(n) == 1) { node *name_node = CHILD(n, 0); name = NEW_IDENTIFIER(name_node); if (!name) return NULL; if (store && forbidden_name(c, name, name_node, 0)) return NULL; return alias(name, NULL, c->c_arena); } else { /* Create a string of the form "a.b.c" */ int i; size_t len; char *s; PyObject *uni; len = 0; for (i = 0; i < NCH(n); i += 2) /* length of string plus one for the dot */ len += strlen(STR(CHILD(n, i))) + 1; len--; /* the last name doesn't have a dot */ str = PyBytes_FromStringAndSize(NULL, len); if (!str) return NULL; s = PyBytes_AS_STRING(str); if (!s) return NULL; for (i = 0; i < NCH(n); i += 2) { char *sch = STR(CHILD(n, i)); strcpy(s, STR(CHILD(n, i))); s += strlen(sch); *s++ = '.'; } --s; *s = '\0'; uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str), PyBytes_GET_SIZE(str), NULL); Py_DECREF(str); if (!uni) return NULL; str = uni; PyUnicode_InternInPlace(&str); if (PyArena_AddPyObject(c->c_arena, str) < 0) { Py_DECREF(str); return NULL; } return alias(str, NULL, c->c_arena); } break; case STAR: str = PyUnicode_InternFromString("*"); if (!str) return NULL; if (PyArena_AddPyObject(c->c_arena, str) < 0) { Py_DECREF(str); return NULL; } return alias(str, NULL, c->c_arena); default: PyErr_Format(PyExc_SystemError, "unexpected import name: %d", TYPE(n)); return NULL; } PyErr_SetString(PyExc_SystemError, "unhandled import name condition"); return NULL; } static stmt_ty ast_for_import_stmt(struct compiling *c, const node *n) { /* import_stmt: import_name | import_from import_name: 'import' dotted_as_names import_from: 'from' (('.' | '...')* dotted_name | ('.' | '...')+) 'import' ('*' | '(' import_as_names ')' | import_as_names) */ int lineno; int col_offset; int i; asdl_seq *aliases; REQ(n, import_stmt); lineno = LINENO(n); col_offset = n->n_col_offset; n = CHILD(n, 0); if (TYPE(n) == import_name) { n = CHILD(n, 1); REQ(n, dotted_as_names); aliases = _Py_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena); if (!aliases) return NULL; for (i = 0; i < NCH(n); i += 2) { alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1); if (!import_alias) return NULL; asdl_seq_SET(aliases, i / 2, import_alias); } return Import(aliases, lineno, col_offset, c->c_arena); } else if (TYPE(n) == import_from) { int n_children; int idx, ndots = 0; alias_ty mod = NULL; identifier modname = NULL; /* Count the number of dots (for relative imports) and check for the optional module name */ for (idx = 1; idx < NCH(n); idx++) { if (TYPE(CHILD(n, idx)) == dotted_name) { mod = alias_for_import_name(c, CHILD(n, idx), 0); if (!mod) return NULL; idx++; break; } else if (TYPE(CHILD(n, idx)) == ELLIPSIS) { /* three consecutive dots are tokenized as one ELLIPSIS */ ndots += 3; continue; } else if (TYPE(CHILD(n, idx)) != DOT) { break; } ndots++; } idx++; /* skip over the 'import' keyword */ switch (TYPE(CHILD(n, idx))) { case STAR: /* from ... import * */ n = CHILD(n, idx); n_children = 1; break; case LPAR: /* from ... import (x, y, z) */ n = CHILD(n, idx + 1); n_children = NCH(n); break; case import_as_names: /* from ... import x, y, z */ n = CHILD(n, idx); n_children = NCH(n); if (n_children % 2 == 0) { ast_error(c, n, "trailing comma not allowed without" " surrounding parentheses"); return NULL; } break; default: ast_error(c, n, "Unexpected node-type in from-import"); return NULL; } aliases = _Py_asdl_seq_new((n_children + 1) / 2, c->c_arena); if (!aliases) return NULL; /* handle "from ... import *" special b/c there's no children */ if (TYPE(n) == STAR) { alias_ty import_alias = alias_for_import_name(c, n, 1); if (!import_alias) return NULL; asdl_seq_SET(aliases, 0, import_alias); } else { for (i = 0; i < NCH(n); i += 2) { alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1); if (!import_alias) return NULL; asdl_seq_SET(aliases, i / 2, import_alias); } } if (mod != NULL) modname = mod->name; return ImportFrom(modname, aliases, ndots, lineno, col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "unknown import statement: starts with command '%s'", STR(CHILD(n, 0))); return NULL; } static stmt_ty ast_for_global_stmt(struct compiling *c, const node *n) { /* global_stmt: 'global' NAME (',' NAME)* */ identifier name; asdl_seq *s; int i; REQ(n, global_stmt); s = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena); if (!s) return NULL; for (i = 1; i < NCH(n); i += 2) { name = NEW_IDENTIFIER(CHILD(n, i)); if (!name) return NULL; asdl_seq_SET(s, i / 2, name); } return Global(s, LINENO(n), n->n_col_offset, c->c_arena); } static stmt_ty ast_for_nonlocal_stmt(struct compiling *c, const node *n) { /* nonlocal_stmt: 'nonlocal' NAME (',' NAME)* */ identifier name; asdl_seq *s; int i; REQ(n, nonlocal_stmt); s = _Py_asdl_seq_new(NCH(n) / 2, c->c_arena); if (!s) return NULL; for (i = 1; i < NCH(n); i += 2) { name = NEW_IDENTIFIER(CHILD(n, i)); if (!name) return NULL; asdl_seq_SET(s, i / 2, name); } return Nonlocal(s, LINENO(n), n->n_col_offset, c->c_arena); } static stmt_ty ast_for_assert_stmt(struct compiling *c, const node *n) { /* assert_stmt: 'assert' test [',' test] */ REQ(n, assert_stmt); if (NCH(n) == 2) { expr_ty expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; return Assert(expression, NULL, LINENO(n), n->n_col_offset, c->c_arena); } else if (NCH(n) == 4) { expr_ty expr1, expr2; expr1 = ast_for_expr(c, CHILD(n, 1)); if (!expr1) return NULL; expr2 = ast_for_expr(c, CHILD(n, 3)); if (!expr2) return NULL; return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "improper number of parts to 'assert' statement: %d", NCH(n)); return NULL; } static asdl_seq * ast_for_suite(struct compiling *c, const node *n) { /* suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT */ asdl_seq *seq; stmt_ty s; int i, total, num, end, pos = 0; node *ch; REQ(n, suite); total = num_stmts(n); seq = _Py_asdl_seq_new(total, c->c_arena); if (!seq) return NULL; if (TYPE(CHILD(n, 0)) == simple_stmt) { n = CHILD(n, 0); /* simple_stmt always ends with a NEWLINE, and may have a trailing SEMI */ end = NCH(n) - 1; if (TYPE(CHILD(n, end - 1)) == SEMI) end--; /* loop by 2 to skip semi-colons */ for (i = 0; i < end; i += 2) { ch = CHILD(n, i); s = ast_for_stmt(c, ch); if (!s) return NULL; asdl_seq_SET(seq, pos++, s); } } else { for (i = 2; i < (NCH(n) - 1); i++) { ch = CHILD(n, i); REQ(ch, stmt); num = num_stmts(ch); if (num == 1) { /* small_stmt or compound_stmt with only one child */ s = ast_for_stmt(c, ch); if (!s) return NULL; asdl_seq_SET(seq, pos++, s); } else { int j; ch = CHILD(ch, 0); REQ(ch, simple_stmt); for (j = 0; j < NCH(ch); j += 2) { /* statement terminates with a semi-colon ';' */ if (NCH(CHILD(ch, j)) == 0) { assert((j + 1) == NCH(ch)); break; } s = ast_for_stmt(c, CHILD(ch, j)); if (!s) return NULL; asdl_seq_SET(seq, pos++, s); } } } } assert(pos == seq->size); return seq; } static stmt_ty ast_for_if_stmt(struct compiling *c, const node *n) { /* if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] */ char *s; REQ(n, if_stmt); if (NCH(n) == 4) { expr_ty expression; asdl_seq *suite_seq; expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); } s = STR(CHILD(n, 4)); /* s[2], the third character in the string, will be 's' for el_s_e, or 'i' for el_i_f */ if (s[2] == 's') { expr_ty expression; asdl_seq *seq1, *seq2; expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; seq1 = ast_for_suite(c, CHILD(n, 3)); if (!seq1) return NULL; seq2 = ast_for_suite(c, CHILD(n, 6)); if (!seq2) return NULL; return If(expression, seq1, seq2, LINENO(n), n->n_col_offset, c->c_arena); } else if (s[2] == 'i') { int i, n_elif, has_else = 0; expr_ty expression; asdl_seq *suite_seq; asdl_seq *orelse = NULL; n_elif = NCH(n) - 4; /* must reference the child n_elif+1 since 'else' token is third, not fourth, child from the end. */ if (TYPE(CHILD(n, (n_elif + 1))) == NAME && STR(CHILD(n, (n_elif + 1)))[2] == 's') { has_else = 1; n_elif -= 3; } n_elif /= 4; if (has_else) { asdl_seq *suite_seq2; orelse = _Py_asdl_seq_new(1, c->c_arena); if (!orelse) return NULL; expression = ast_for_expr(c, CHILD(n, NCH(n) - 6)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, NCH(n) - 4)); if (!suite_seq) return NULL; suite_seq2 = ast_for_suite(c, CHILD(n, NCH(n) - 1)); if (!suite_seq2) return NULL; asdl_seq_SET(orelse, 0, If(expression, suite_seq, suite_seq2, LINENO(CHILD(n, NCH(n) - 6)), CHILD(n, NCH(n) - 6)->n_col_offset, c->c_arena)); /* the just-created orelse handled the last elif */ n_elif--; } for (i = 0; i < n_elif; i++) { int off = 5 + (n_elif - i - 1) * 4; asdl_seq *newobj = _Py_asdl_seq_new(1, c->c_arena); if (!newobj) return NULL; expression = ast_for_expr(c, CHILD(n, off)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, off + 2)); if (!suite_seq) return NULL; asdl_seq_SET(newobj, 0, If(expression, suite_seq, orelse, LINENO(CHILD(n, off)), CHILD(n, off)->n_col_offset, c->c_arena)); orelse = newobj; } expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; return If(expression, suite_seq, orelse, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "unexpected token in 'if' statement: %s", s); return NULL; } static stmt_ty ast_for_while_stmt(struct compiling *c, const node *n) { /* while_stmt: 'while' test ':' suite ['else' ':' suite] */ REQ(n, while_stmt); if (NCH(n) == 4) { expr_ty expression; asdl_seq *suite_seq; expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, 3)); if (!suite_seq) return NULL; return While(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena); } else if (NCH(n) == 7) { expr_ty expression; asdl_seq *seq1, *seq2; expression = ast_for_expr(c, CHILD(n, 1)); if (!expression) return NULL; seq1 = ast_for_suite(c, CHILD(n, 3)); if (!seq1) return NULL; seq2 = ast_for_suite(c, CHILD(n, 6)); if (!seq2) return NULL; return While(expression, seq1, seq2, LINENO(n), n->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "wrong number of tokens for 'while' statement: %d", NCH(n)); return NULL; } static stmt_ty ast_for_for_stmt(struct compiling *c, const node *n, int is_async) { asdl_seq *_target, *seq = NULL, *suite_seq; expr_ty expression; expr_ty target, first; const node *node_target; /* for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] */ REQ(n, for_stmt); if (NCH(n) == 9) { seq = ast_for_suite(c, CHILD(n, 8)); if (!seq) return NULL; } node_target = CHILD(n, 1); _target = ast_for_exprlist(c, node_target, Store); if (!_target) return NULL; /* Check the # of children rather than the length of _target, since for x, in ... has 1 element in _target, but still requires a Tuple. */ first = (expr_ty)asdl_seq_GET(_target, 0); if (NCH(node_target) == 1) target = first; else target = Tuple(_target, Store, first->lineno, first->col_offset, c->c_arena); expression = ast_for_testlist(c, CHILD(n, 3)); if (!expression) return NULL; suite_seq = ast_for_suite(c, CHILD(n, 5)); if (!suite_seq) return NULL; if (is_async) return AsyncFor(target, expression, suite_seq, seq, LINENO(n), n->n_col_offset, c->c_arena); else return For(target, expression, suite_seq, seq, LINENO(n), n->n_col_offset, c->c_arena); } static excepthandler_ty ast_for_except_clause(struct compiling *c, const node *exc, node *body) { /* except_clause: 'except' [test ['as' test]] */ REQ(exc, except_clause); REQ(body, suite); if (NCH(exc) == 1) { asdl_seq *suite_seq = ast_for_suite(c, body); if (!suite_seq) return NULL; return ExceptHandler(NULL, NULL, suite_seq, LINENO(exc), exc->n_col_offset, c->c_arena); } else if (NCH(exc) == 2) { expr_ty expression; asdl_seq *suite_seq; expression = ast_for_expr(c, CHILD(exc, 1)); if (!expression) return NULL; suite_seq = ast_for_suite(c, body); if (!suite_seq) return NULL; return ExceptHandler(expression, NULL, suite_seq, LINENO(exc), exc->n_col_offset, c->c_arena); } else if (NCH(exc) == 4) { asdl_seq *suite_seq; expr_ty expression; identifier e = NEW_IDENTIFIER(CHILD(exc, 3)); if (!e) return NULL; if (forbidden_name(c, e, CHILD(exc, 3), 0)) return NULL; expression = ast_for_expr(c, CHILD(exc, 1)); if (!expression) return NULL; suite_seq = ast_for_suite(c, body); if (!suite_seq) return NULL; return ExceptHandler(expression, e, suite_seq, LINENO(exc), exc->n_col_offset, c->c_arena); } PyErr_Format(PyExc_SystemError, "wrong number of children for 'except' clause: %d", NCH(exc)); return NULL; } static stmt_ty ast_for_try_stmt(struct compiling *c, const node *n) { const int nch = NCH(n); int n_except = (nch - 3)/3; asdl_seq *body, *handlers = NULL, *orelse = NULL, *finally = NULL; REQ(n, try_stmt); body = ast_for_suite(c, CHILD(n, 2)); if (body == NULL) return NULL; if (TYPE(CHILD(n, nch - 3)) == NAME) { if (strcmp(STR(CHILD(n, nch - 3)), "finally") == 0) { if (nch >= 9 && TYPE(CHILD(n, nch - 6)) == NAME) { /* we can assume it's an "else", because nch >= 9 for try-else-finally and it would otherwise have a type of except_clause */ orelse = ast_for_suite(c, CHILD(n, nch - 4)); if (orelse == NULL) return NULL; n_except--; } finally = ast_for_suite(c, CHILD(n, nch - 1)); if (finally == NULL) return NULL; n_except--; } else { /* we can assume it's an "else", otherwise it would have a type of except_clause */ orelse = ast_for_suite(c, CHILD(n, nch - 1)); if (orelse == NULL) return NULL; n_except--; } } else if (TYPE(CHILD(n, nch - 3)) != except_clause) { ast_error(c, n, "malformed 'try' statement"); return NULL; } if (n_except > 0) { int i; /* process except statements to create a try ... except */ handlers = _Py_asdl_seq_new(n_except, c->c_arena); if (handlers == NULL) return NULL; for (i = 0; i < n_except; i++) { excepthandler_ty e = ast_for_except_clause(c, CHILD(n, 3 + i * 3), CHILD(n, 5 + i * 3)); if (!e) return NULL; asdl_seq_SET(handlers, i, e); } } assert(finally != NULL || asdl_seq_LEN(handlers)); return Try(body, handlers, orelse, finally, LINENO(n), n->n_col_offset, c->c_arena); } /* with_item: test ['as' expr] */ static withitem_ty ast_for_with_item(struct compiling *c, const node *n) { expr_ty context_expr, optional_vars = NULL; REQ(n, with_item); context_expr = ast_for_expr(c, CHILD(n, 0)); if (!context_expr) return NULL; if (NCH(n) == 3) { optional_vars = ast_for_expr(c, CHILD(n, 2)); if (!optional_vars) { return NULL; } if (!set_context(c, optional_vars, Store, n)) { return NULL; } } return withitem(context_expr, optional_vars, c->c_arena); } /* with_stmt: 'with' with_item (',' with_item)* ':' suite */ static stmt_ty ast_for_with_stmt(struct compiling *c, const node *n, int is_async) { int i, n_items; asdl_seq *items, *body; REQ(n, with_stmt); n_items = (NCH(n) - 2) / 2; items = _Py_asdl_seq_new(n_items, c->c_arena); if (!items) return NULL; for (i = 1; i < NCH(n) - 2; i += 2) { withitem_ty item = ast_for_with_item(c, CHILD(n, i)); if (!item) return NULL; asdl_seq_SET(items, (i - 1) / 2, item); } body = ast_for_suite(c, CHILD(n, NCH(n) - 1)); if (!body) return NULL; if (is_async) return AsyncWith(items, body, LINENO(n), n->n_col_offset, c->c_arena); else return With(items, body, LINENO(n), n->n_col_offset, c->c_arena); } static stmt_ty ast_for_classdef(struct compiling *c, const node *n, asdl_seq *decorator_seq) { /* classdef: 'class' NAME ['(' arglist ')'] ':' suite */ PyObject *classname; asdl_seq *s; expr_ty call; REQ(n, classdef); if (NCH(n) == 4) { /* class NAME ':' suite */ s = ast_for_suite(c, CHILD(n, 3)); if (!s) return NULL; classname = NEW_IDENTIFIER(CHILD(n, 1)); if (!classname) return NULL; if (forbidden_name(c, classname, CHILD(n, 3), 0)) return NULL; return ClassDef(classname, NULL, NULL, s, decorator_seq, LINENO(n), n->n_col_offset, c->c_arena); } if (TYPE(CHILD(n, 3)) == RPAR) { /* class NAME '(' ')' ':' suite */ s = ast_for_suite(c, CHILD(n,5)); if (!s) return NULL; classname = NEW_IDENTIFIER(CHILD(n, 1)); if (!classname) return NULL; if (forbidden_name(c, classname, CHILD(n, 3), 0)) return NULL; return ClassDef(classname, NULL, NULL, s, decorator_seq, LINENO(n), n->n_col_offset, c->c_arena); } /* class NAME '(' arglist ')' ':' suite */ /* build up a fake Call node so we can extract its pieces */ { PyObject *dummy_name; expr_ty dummy; dummy_name = NEW_IDENTIFIER(CHILD(n, 1)); if (!dummy_name) return NULL; dummy = Name(dummy_name, Load, LINENO(n), n->n_col_offset, c->c_arena); call = ast_for_call(c, CHILD(n, 3), dummy); if (!call) return NULL; } s = ast_for_suite(c, CHILD(n, 6)); if (!s) return NULL; classname = NEW_IDENTIFIER(CHILD(n, 1)); if (!classname) return NULL; if (forbidden_name(c, classname, CHILD(n, 1), 0)) return NULL; return ClassDef(classname, call->v.Call.args, call->v.Call.keywords, s, decorator_seq, LINENO(n), n->n_col_offset, c->c_arena); } static stmt_ty ast_for_stmt(struct compiling *c, const node *n) { if (TYPE(n) == stmt) { assert(NCH(n) == 1); n = CHILD(n, 0); } if (TYPE(n) == simple_stmt) { assert(num_stmts(n) == 1); n = CHILD(n, 0); } if (TYPE(n) == small_stmt) { n = CHILD(n, 0); /* small_stmt: expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt */ switch (TYPE(n)) { case expr_stmt: return ast_for_expr_stmt(c, n); case del_stmt: return ast_for_del_stmt(c, n); case pass_stmt: return Pass(LINENO(n), n->n_col_offset, c->c_arena); case flow_stmt: return ast_for_flow_stmt(c, n); case import_stmt: return ast_for_import_stmt(c, n); case global_stmt: return ast_for_global_stmt(c, n); case nonlocal_stmt: return ast_for_nonlocal_stmt(c, n); case assert_stmt: return ast_for_assert_stmt(c, n); default: PyErr_Format(PyExc_SystemError, "unhandled small_stmt: TYPE=%d NCH=%d\n", TYPE(n), NCH(n)); return NULL; } } else { /* compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef | decorated | async_stmt */ node *ch = CHILD(n, 0); REQ(n, compound_stmt); switch (TYPE(ch)) { case if_stmt: return ast_for_if_stmt(c, ch); case while_stmt: return ast_for_while_stmt(c, ch); case for_stmt: return ast_for_for_stmt(c, ch, 0); case try_stmt: return ast_for_try_stmt(c, ch); case with_stmt: return ast_for_with_stmt(c, ch, 0); case funcdef: return ast_for_funcdef(c, ch, NULL); case classdef: return ast_for_classdef(c, ch, NULL); case decorated: return ast_for_decorated(c, ch); case async_stmt: return ast_for_async_stmt(c, ch); default: PyErr_Format(PyExc_SystemError, "unhandled small_stmt: TYPE=%d NCH=%d\n", TYPE(n), NCH(n)); return NULL; } } } static PyObject * parsenumber_raw(struct compiling *c, const char *s) { const char *end; long x; double dx; Py_complex compl; int imflag; assert(s != NULL); errno = 0; end = s + strlen(s) - 1; imflag = *end == 'j' || *end == 'J'; if (s[0] == '0') { x = (long) PyOS_strtoul(s, (char **)&end, 0); if (x < 0 && errno == 0) { return PyLong_FromString(s, (char **)0, 0); } } else x = PyOS_strtol(s, (char **)&end, 0); if (*end == '\0') { if (errno != 0) return PyLong_FromString(s, (char **)0, 0); return PyLong_FromLong(x); } /* XXX Huge floats may silently fail */ if (imflag) { compl.real = 0.; compl.imag = PyOS_string_to_double(s, (char **)&end, NULL); if (compl.imag == -1.0 && PyErr_Occurred()) return NULL; return PyComplex_FromCComplex(compl); } else { dx = PyOS_string_to_double(s, NULL, NULL); if (dx == -1.0 && PyErr_Occurred()) return NULL; return PyFloat_FromDouble(dx); } } static PyObject * parsenumber(struct compiling *c, const char *s) { char *dup, *end; PyObject *res = NULL; assert(s != NULL); if (strchr(s, '_') == NULL) { return parsenumber_raw(c, s); } /* Create a duplicate without underscores. */ dup = PyMem_Malloc(strlen(s) + 1); if (dup == NULL) { return PyErr_NoMemory(); } end = dup; for (; *s; s++) { if (*s != '_') { *end++ = *s; } } *end = '\0'; res = parsenumber_raw(c, dup); PyMem_Free(dup); return res; } static PyObject * decode_utf8(struct compiling *c, const char **sPtr, const char *end) { const char *s, *t; t = s = *sPtr; /* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */ while (s < end && (*s & 0x80)) s++; *sPtr = s; return PyUnicode_DecodeUTF8(t, s - t, NULL); } static int warn_invalid_escape_sequence(struct compiling *c, const node *n, unsigned char first_invalid_escape_char) { PyObject *msg = PyUnicode_FromFormat("invalid escape sequence \\%c", first_invalid_escape_char); if (msg == NULL) { return -1; } if (PyErr_WarnExplicitObject(PyExc_DeprecationWarning, msg, c->c_filename, LINENO(n), NULL, NULL) < 0) { if (PyErr_ExceptionMatches(PyExc_DeprecationWarning)) { const char *s; /* Replace the DeprecationWarning exception with a SyntaxError to get a more accurate error report */ PyErr_Clear(); s = PyUnicode_AsUTF8(msg); if (s != NULL) { ast_error(c, n, s); } } Py_DECREF(msg); return -1; } Py_DECREF(msg); return 0; } static PyObject * decode_unicode_with_escapes(struct compiling *c, const node *n, const char *s, size_t len) { PyObject *v, *u; char *buf; char *p; const char *end; /* check for integer overflow */ if (len > SIZE_MAX / 6) return NULL; /* "ä" (2 bytes) may become "\U000000E4" (10 bytes), or 1:5 "\ä" (3 bytes) may become "\u005c\U000000E4" (16 bytes), or ~1:6 */ u = PyBytes_FromStringAndSize((char *)NULL, len * 6); if (u == NULL) return NULL; p = buf = PyBytes_AsString(u); end = s + len; while (s < end) { if (*s == '\\') { *p++ = *s++; if (s >= end || *s & 0x80) { strcpy(p, "u005c"); p += 5; if (s >= end) break; } } if (*s & 0x80) { /* XXX inefficient */ PyObject *w; int kind; void *data; Py_ssize_t len, i; w = decode_utf8(c, &s, end); if (w == NULL) { Py_DECREF(u); return NULL; } kind = PyUnicode_KIND(w); data = PyUnicode_DATA(w); len = PyUnicode_GET_LENGTH(w); for (i = 0; i < len; i++) { Py_UCS4 chr = PyUnicode_READ(kind, data, i); sprintf(p, "\\U%08x", chr); p += 10; } /* Should be impossible to overflow */ assert(p - buf <= Py_SIZE(u)); Py_DECREF(w); } else { *p++ = *s++; } } len = p - buf; s = buf; const char *first_invalid_escape; v = _PyUnicode_DecodeUnicodeEscape(s, len, NULL, &first_invalid_escape); if (v != NULL && first_invalid_escape != NULL) { if (warn_invalid_escape_sequence(c, n, *first_invalid_escape) < 0) { /* We have not decref u before because first_invalid_escape points inside u. */ Py_XDECREF(u); Py_DECREF(v); return NULL; } } Py_XDECREF(u); return v; } static PyObject * decode_bytes_with_escapes(struct compiling *c, const node *n, const char *s, size_t len) { const char *first_invalid_escape; PyObject *result = _PyBytes_DecodeEscape(s, len, NULL, 0, NULL, &first_invalid_escape); if (result == NULL) return NULL; if (first_invalid_escape != NULL) { if (warn_invalid_escape_sequence(c, n, *first_invalid_escape) < 0) { Py_DECREF(result); return NULL; } } return result; } /* Shift locations for the given node and all its children by adding `lineno` and `col_offset` to existing locations. */ static void fstring_shift_node_locations(node *n, int lineno, int col_offset) { n->n_col_offset = n->n_col_offset + col_offset; for (int i = 0; i < NCH(n); ++i) { if (n->n_lineno && n->n_lineno < CHILD(n, i)->n_lineno) { /* Shifting column offsets unnecessary if there's been newlines. */ col_offset = 0; } fstring_shift_node_locations(CHILD(n, i), lineno, col_offset); } n->n_lineno = n->n_lineno + lineno; } /* Fix locations for the given node and its children. `parent` is the enclosing node. `n` is the node which locations are going to be fixed relative to parent. `expr_str` is the child node's string representation, incuding braces. */ static void fstring_fix_node_location(const node *parent, node *n, char *expr_str) { char *substr = NULL; char *start; int lines = LINENO(parent) - 1; int cols = parent->n_col_offset; /* Find the full fstring to fix location information in `n`. */ while (parent && parent->n_type != STRING) parent = parent->n_child; if (parent && parent->n_str) { substr = strstr(parent->n_str, expr_str); if (substr) { start = substr; while (start > parent->n_str) { if (start[0] == '\n') break; start--; } cols += substr - start; /* Fix lineno in mulitline strings. */ while ((substr = strchr(substr + 1, '\n'))) lines--; } } fstring_shift_node_locations(n, lines, cols); } /* Compile this expression in to an expr_ty. Add parens around the expression, in order to allow leading spaces in the expression. */ static expr_ty fstring_compile_expr(const char *expr_start, const char *expr_end, struct compiling *c, const node *n) { PyCompilerFlags cf; node *mod_n; mod_ty mod; char *str; Py_ssize_t len; const char *s; assert(expr_end >= expr_start); assert(*(expr_start-1) == '{'); assert(*expr_end == '}' || *expr_end == '!' || *expr_end == ':'); /* If the substring is all whitespace, it's an error. We need to catch this here, and not when we call PyParser_SimpleParseStringFlagsFilename, because turning the expression '' in to '()' would go from being invalid to valid. */ for (s = expr_start; s != expr_end; s++) { char c = *s; /* The Python parser ignores only the following whitespace characters (\r already is converted to \n). */ if (!(c == ' ' || c == '\t' || c == '\n' || c == '\f')) { break; } } if (s == expr_end) { ast_error(c, n, "f-string: empty expression not allowed"); return NULL; } len = expr_end - expr_start; /* Allocate 3 extra bytes: open paren, close paren, null byte. */ str = PyMem_RawMalloc(len + 3); if (str == NULL) { PyErr_NoMemory(); return NULL; } str[0] = '('; memcpy(str+1, expr_start, len); str[len+1] = ')'; str[len+2] = 0; cf.cf_flags = PyCF_ONLY_AST; mod_n = PyParser_SimpleParseStringFlagsFilename(str, "<fstring>", Py_eval_input, 0); if (!mod_n) { PyMem_RawFree(str); return NULL; } /* Reuse str to find the correct column offset. */ str[0] = '{'; str[len+1] = '}'; fstring_fix_node_location(n, mod_n, str); mod = PyAST_FromNode(mod_n, &cf, "<fstring>", c->c_arena); PyMem_RawFree(str); PyNode_Free(mod_n); if (!mod) return NULL; return mod->v.Expression.body; } /* Return -1 on error. Return 0 if we reached the end of the literal. Return 1 if we haven't reached the end of the literal, but we want the caller to process the literal up to this point. Used for doubled braces. */ static int fstring_find_literal(const char **str, const char *end, int raw, PyObject **literal, int recurse_lvl, struct compiling *c, const node *n) { /* Get any literal string. It ends when we hit an un-doubled left brace (which isn't part of a unicode name escape such as "\N{EULER CONSTANT}"), or the end of the string. */ const char *s = *str; const char *literal_start = s; int result = 0; assert(*literal == NULL); while (s < end) { char ch = *s++; if (!raw && ch == '\\' && s < end) { ch = *s++; if (ch == 'N') { if (s < end && *s++ == '{') { while (s < end && *s++ != '}') { } continue; } break; } if (ch == '{' && warn_invalid_escape_sequence(c, n, ch) < 0) { return -1; } } if (ch == '{' || ch == '}') { /* Check for doubled braces, but only at the top level. If we checked at every level, then f'{0:{3}}' would fail with the two closing braces. */ if (recurse_lvl == 0) { if (s < end && *s == ch) { /* We're going to tell the caller that the literal ends here, but that they should continue scanning. But also skip over the second brace when we resume scanning. */ *str = s + 1; result = 1; goto done; } /* Where a single '{' is the start of a new expression, a single '}' is not allowed. */ if (ch == '}') { *str = s - 1; ast_error(c, n, "f-string: single '}' is not allowed"); return -1; } } /* We're either at a '{', which means we're starting another expression; or a '}', which means we're at the end of this f-string (for a nested format_spec). */ s--; break; } } *str = s; assert(s <= end); assert(s == end || *s == '{' || *s == '}'); done: if (literal_start != s) { if (raw) *literal = PyUnicode_DecodeUTF8Stateful(literal_start, s - literal_start, NULL, NULL); else *literal = decode_unicode_with_escapes(c, n, literal_start, s - literal_start); if (!*literal) return -1; } return result; } /* Forward declaration because parsing is recursive. */ static expr_ty fstring_parse(const char **str, const char *end, int raw, int recurse_lvl, struct compiling *c, const node *n); /* Parse the f-string at *str, ending at end. We know *str starts an expression (so it must be a '{'). Returns the FormattedValue node, which includes the expression, conversion character, and format_spec expression. Note that I don't do a perfect job here: I don't make sure that a closing brace doesn't match an opening paren, for example. It doesn't need to error on all invalid expressions, just correctly find the end of all valid ones. Any errors inside the expression will be caught when we parse it later. */ static int fstring_find_expr(const char **str, const char *end, int raw, int recurse_lvl, expr_ty *expression, struct compiling *c, const node *n) { /* Return -1 on error, else 0. */ const char *expr_start; const char *expr_end; expr_ty simple_expression; expr_ty format_spec = NULL; /* Optional format specifier. */ int conversion = -1; /* The conversion char. -1 if not specified. */ /* 0 if we're not in a string, else the quote char we're trying to match (single or double quote). */ char quote_char = 0; /* If we're inside a string, 1=normal, 3=triple-quoted. */ int string_type = 0; /* Keep track of nesting level for braces/parens/brackets in expressions. */ Py_ssize_t nested_depth = 0; /* Can only nest one level deep. */ if (recurse_lvl >= 2) { ast_error(c, n, "f-string: expressions nested too deeply"); return -1; } /* The first char must be a left brace, or we wouldn't have gotten here. Skip over it. */ assert(**str == '{'); *str += 1; expr_start = *str; for (; *str < end; (*str)++) { char ch; /* Loop invariants. */ assert(nested_depth >= 0); assert(*str >= expr_start && *str < end); if (quote_char) assert(string_type == 1 || string_type == 3); else assert(string_type == 0); ch = **str; /* Nowhere inside an expression is a backslash allowed. */ if (ch == '\\') { /* Error: can't include a backslash character, inside parens or strings or not. */ ast_error(c, n, "f-string expression part " "cannot include a backslash"); return -1; } if (quote_char) { /* We're inside a string. See if we're at the end. */ /* This code needs to implement the same non-error logic as tok_get from tokenizer.c, at the letter_quote label. To actually share that code would be a nightmare. But, it's unlikely to change and is small, so duplicate it here. Note we don't need to catch all of the errors, since they'll be caught when parsing the expression. We just need to match the non-error cases. Thus we can ignore \n in single-quoted strings, for example. Or non-terminated strings. */ if (ch == quote_char) { /* Does this match the string_type (single or triple quoted)? */ if (string_type == 3) { if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) { /* We're at the end of a triple quoted string. */ *str += 2; string_type = 0; quote_char = 0; continue; } } else { /* We're at the end of a normal string. */ quote_char = 0; string_type = 0; continue; } } } else if (ch == '\'' || ch == '"') { /* Is this a triple quoted string? */ if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) { string_type = 3; *str += 2; } else { /* Start of a normal string. */ string_type = 1; } /* Start looking for the end of the string. */ quote_char = ch; } else if (ch == '[' || ch == '{' || ch == '(') { nested_depth++; } else if (nested_depth != 0 && (ch == ']' || ch == '}' || ch == ')')) { nested_depth--; } else if (ch == '#') { /* Error: can't include a comment character, inside parens or not. */ ast_error(c, n, "f-string expression part cannot include '#'"); return -1; } else if (nested_depth == 0 && (ch == '!' || ch == ':' || ch == '}')) { /* First, test for the special case of "!=". Since '=' is not an allowed conversion character, nothing is lost in this test. */ if (ch == '!' && *str+1 < end && *(*str+1) == '=') { /* This isn't a conversion character, just continue. */ continue; } /* Normal way out of this loop. */ break; } else { /* Just consume this char and loop around. */ } } expr_end = *str; /* If we leave this loop in a string or with mismatched parens, we don't care. We'll get a syntax error when compiling the expression. But, we can produce a better error message, so let's just do that.*/ if (quote_char) { ast_error(c, n, "f-string: unterminated string"); return -1; } if (nested_depth) { ast_error(c, n, "f-string: mismatched '(', '{', or '['"); return -1; } if (*str >= end) goto unexpected_end_of_string; /* Compile the expression as soon as possible, so we show errors related to the expression before errors related to the conversion or format_spec. */ simple_expression = fstring_compile_expr(expr_start, expr_end, c, n); if (!simple_expression) return -1; /* Check for a conversion char, if present. */ if (**str == '!') { *str += 1; if (*str >= end) goto unexpected_end_of_string; conversion = **str; *str += 1; /* Validate the conversion. */ if (!(conversion == 's' || conversion == 'r' || conversion == 'a')) { ast_error(c, n, "f-string: invalid conversion character: " "expected 's', 'r', or 'a'"); return -1; } } /* Check for the format spec, if present. */ if (*str >= end) goto unexpected_end_of_string; if (**str == ':') { *str += 1; if (*str >= end) goto unexpected_end_of_string; /* Parse the format spec. */ format_spec = fstring_parse(str, end, raw, recurse_lvl+1, c, n); if (!format_spec) return -1; } if (*str >= end || **str != '}') goto unexpected_end_of_string; /* We're at a right brace. Consume it. */ assert(*str < end); assert(**str == '}'); *str += 1; /* And now create the FormattedValue node that represents this entire expression with the conversion and format spec. */ *expression = FormattedValue(simple_expression, conversion, format_spec, LINENO(n), n->n_col_offset, c->c_arena); if (!*expression) return -1; return 0; unexpected_end_of_string: ast_error(c, n, "f-string: expecting '}'"); return -1; } /* Return -1 on error. Return 0 if we have a literal (possible zero length) and an expression (zero length if at the end of the string. Return 1 if we have a literal, but no expression, and we want the caller to call us again. This is used to deal with doubled braces. When called multiple times on the string 'a{{b{0}c', this function will return: 1. the literal 'a{' with no expression, and a return value of 1. Despite the fact that there's no expression, the return value of 1 means we're not finished yet. 2. the literal 'b' and the expression '0', with a return value of 0. The fact that there's an expression means we're not finished. 3. literal 'c' with no expression and a return value of 0. The combination of the return value of 0 with no expression means we're finished. */ static int fstring_find_literal_and_expr(const char **str, const char *end, int raw, int recurse_lvl, PyObject **literal, expr_ty *expression, struct compiling *c, const node *n) { int result; assert(*literal == NULL && *expression == NULL); /* Get any literal string. */ result = fstring_find_literal(str, end, raw, literal, recurse_lvl, c, n); if (result < 0) goto error; assert(result == 0 || result == 1); if (result == 1) /* We have a literal, but don't look at the expression. */ return 1; if (*str >= end || **str == '}') /* We're at the end of the string or the end of a nested f-string: no expression. The top-level error case where we expect to be at the end of the string but we're at a '}' is handled later. */ return 0; /* We must now be the start of an expression, on a '{'. */ assert(**str == '{'); if (fstring_find_expr(str, end, raw, recurse_lvl, expression, c, n) < 0) goto error; return 0; error: Py_CLEAR(*literal); return -1; } #define EXPRLIST_N_CACHED 64 typedef struct { /* Incrementally build an array of expr_ty, so be used in an asdl_seq. Cache some small but reasonably sized number of expr_ty's, and then after that start dynamically allocating, doubling the number allocated each time. Note that the f-string f'{0}a{1}' contains 3 expr_ty's: 2 FormattedValue's, and one Str for the literal 'a'. So you add expr_ty's about twice as fast as you add exressions in an f-string. */ Py_ssize_t allocated; /* Number we've allocated. */ Py_ssize_t size; /* Number we've used. */ expr_ty *p; /* Pointer to the memory we're actually using. Will point to 'data' until we start dynamically allocating. */ expr_ty data[EXPRLIST_N_CACHED]; } ExprList; #ifdef NDEBUG #define ExprList_check_invariants(l) #else static void ExprList_check_invariants(ExprList *l) { /* Check our invariants. Make sure this object is "live", and hasn't been deallocated. */ assert(l->size >= 0); assert(l->p != NULL); if (l->size <= EXPRLIST_N_CACHED) assert(l->data == l->p); } #endif static void ExprList_Init(ExprList *l) { l->allocated = EXPRLIST_N_CACHED; l->size = 0; /* Until we start allocating dynamically, p points to data. */ l->p = l->data; ExprList_check_invariants(l); } static int ExprList_Append(ExprList *l, expr_ty exp) { ExprList_check_invariants(l); if (l->size >= l->allocated) { /* We need to alloc (or realloc) the memory. */ Py_ssize_t new_size = l->allocated * 2; /* See if we've ever allocated anything dynamically. */ if (l->p == l->data) { Py_ssize_t i; /* We're still using the cached data. Switch to alloc-ing. */ l->p = PyMem_RawMalloc(sizeof(expr_ty) * new_size); if (!l->p) return -1; /* Copy the cached data into the new buffer. */ for (i = 0; i < l->size; i++) l->p[i] = l->data[i]; } else { /* Just realloc. */ expr_ty *tmp = PyMem_RawRealloc(l->p, sizeof(expr_ty) * new_size); if (!tmp) { PyMem_RawFree(l->p); l->p = NULL; return -1; } l->p = tmp; } l->allocated = new_size; assert(l->allocated == 2 * l->size); } l->p[l->size++] = exp; ExprList_check_invariants(l); return 0; } static void ExprList_Dealloc(ExprList *l) { ExprList_check_invariants(l); /* If there's been an error, or we've never dynamically allocated, do nothing. */ if (!l->p || l->p == l->data) { /* Do nothing. */ } else { /* We have dynamically allocated. Free the memory. */ PyMem_RawFree(l->p); } l->p = NULL; l->size = -1; } static asdl_seq * ExprList_Finish(ExprList *l, PyArena *arena) { asdl_seq *seq; ExprList_check_invariants(l); /* Allocate the asdl_seq and copy the expressions in to it. */ seq = _Py_asdl_seq_new(l->size, arena); if (seq) { Py_ssize_t i; for (i = 0; i < l->size; i++) asdl_seq_SET(seq, i, l->p[i]); } ExprList_Dealloc(l); return seq; } /* The FstringParser is designed to add a mix of strings and f-strings, and concat them together as needed. Ultimately, it generates an expr_ty. */ typedef struct { PyObject *last_str; ExprList expr_list; int fmode; } FstringParser; #ifdef NDEBUG #define FstringParser_check_invariants(state) #else static void FstringParser_check_invariants(FstringParser *state) { if (state->last_str) assert(PyUnicode_CheckExact(state->last_str)); ExprList_check_invariants(&state->expr_list); } #endif static void FstringParser_Init(FstringParser *state) { state->last_str = NULL; state->fmode = 0; ExprList_Init(&state->expr_list); FstringParser_check_invariants(state); } static void FstringParser_Dealloc(FstringParser *state) { FstringParser_check_invariants(state); Py_XDECREF(state->last_str); ExprList_Dealloc(&state->expr_list); } /* Make a Str node, but decref the PyUnicode object being added. */ static expr_ty make_str_node_and_del(PyObject **str, struct compiling *c, const node* n) { PyObject *s = *str; *str = NULL; assert(PyUnicode_CheckExact(s)); if (PyArena_AddPyObject(c->c_arena, s) < 0) { Py_DECREF(s); return NULL; } return Str(s, LINENO(n), n->n_col_offset, c->c_arena); } /* Add a non-f-string (that is, a regular literal string). str is decref'd. */ static int FstringParser_ConcatAndDel(FstringParser *state, PyObject *str) { FstringParser_check_invariants(state); assert(PyUnicode_CheckExact(str)); if (PyUnicode_GET_LENGTH(str) == 0) { Py_DECREF(str); return 0; } if (!state->last_str) { /* We didn't have a string before, so just remember this one. */ state->last_str = str; } else { /* Concatenate this with the previous string. */ PyUnicode_AppendAndDel(&state->last_str, str); if (!state->last_str) return -1; } FstringParser_check_invariants(state); return 0; } /* Parse an f-string. The f-string is in *str to end, with no 'f' or quotes. */ static int FstringParser_ConcatFstring(FstringParser *state, const char **str, const char *end, int raw, int recurse_lvl, struct compiling *c, const node *n) { FstringParser_check_invariants(state); state->fmode = 1; /* Parse the f-string. */ while (1) { PyObject *literal = NULL; expr_ty expression = NULL; /* If there's a zero length literal in front of the expression, literal will be NULL. If we're at the end of the f-string, expression will be NULL (unless result == 1, see below). */ int result = fstring_find_literal_and_expr(str, end, raw, recurse_lvl, &literal, &expression, c, n); if (result < 0) return -1; /* Add the literal, if any. */ if (!literal) { /* Do nothing. Just leave last_str alone (and possibly NULL). */ } else if (!state->last_str) { /* Note that the literal can be zero length, if the input string is "\\\n" or "\\\r", among others. */ state->last_str = literal; literal = NULL; } else { /* We have a literal, concatenate it. */ assert(PyUnicode_GET_LENGTH(literal) != 0); if (FstringParser_ConcatAndDel(state, literal) < 0) return -1; literal = NULL; } /* We've dealt with the literal now. It can't be leaked on further errors. */ assert(literal == NULL); /* See if we should just loop around to get the next literal and expression, while ignoring the expression this time. This is used for un-doubling braces, as an optimization. */ if (result == 1) continue; if (!expression) /* We're done with this f-string. */ break; /* We know we have an expression. Convert any existing string to a Str node. */ if (!state->last_str) { /* Do nothing. No previous literal. */ } else { /* Convert the existing last_str literal to a Str node. */ expr_ty str = make_str_node_and_del(&state->last_str, c, n); if (!str || ExprList_Append(&state->expr_list, str) < 0) return -1; } if (ExprList_Append(&state->expr_list, expression) < 0) return -1; } /* If recurse_lvl is zero, then we must be at the end of the string. Otherwise, we must be at a right brace. */ if (recurse_lvl == 0 && *str < end-1) { ast_error(c, n, "f-string: unexpected end of string"); return -1; } if (recurse_lvl != 0 && **str != '}') { ast_error(c, n, "f-string: expecting '}'"); return -1; } FstringParser_check_invariants(state); return 0; } /* Convert the partial state reflected in last_str and expr_list to an expr_ty. The expr_ty can be a Str, or a JoinedStr. */ static expr_ty FstringParser_Finish(FstringParser *state, struct compiling *c, const node *n) { asdl_seq *seq; FstringParser_check_invariants(state); /* If we're just a constant string with no expressions, return that. */ if (!state->fmode) { assert(!state->expr_list.size); if (!state->last_str) { /* Create a zero length string. */ state->last_str = PyUnicode_FromStringAndSize(NULL, 0); if (!state->last_str) goto error; } return make_str_node_and_del(&state->last_str, c, n); } /* Create a Str node out of last_str, if needed. It will be the last node in our expression list. */ if (state->last_str) { expr_ty str = make_str_node_and_del(&state->last_str, c, n); if (!str || ExprList_Append(&state->expr_list, str) < 0) goto error; } /* This has already been freed. */ assert(state->last_str == NULL); seq = ExprList_Finish(&state->expr_list, c->c_arena); if (!seq) goto error; return JoinedStr(seq, LINENO(n), n->n_col_offset, c->c_arena); error: FstringParser_Dealloc(state); return NULL; } /* Given an f-string (with no 'f' or quotes) that's in *str and ends at end, parse it into an expr_ty. Return NULL on error. Adjust str to point past the parsed portion. */ static expr_ty fstring_parse(const char **str, const char *end, int raw, int recurse_lvl, struct compiling *c, const node *n) { FstringParser state; FstringParser_Init(&state); if (FstringParser_ConcatFstring(&state, str, end, raw, recurse_lvl, c, n) < 0) { FstringParser_Dealloc(&state); return NULL; } return FstringParser_Finish(&state, c, n); } /* n is a Python string literal, including the bracketing quote characters, and r, b, u, &/or f prefixes (if any), and embedded escape sequences (if any). parsestr parses it, and sets *result to decoded Python string object. If the string is an f-string, set *fstr and *fstrlen to the unparsed string object. Return 0 if no errors occurred. */ static int parsestr(struct compiling *c, const node *n, int *bytesmode, int *rawmode, PyObject **result, const char **fstr, Py_ssize_t *fstrlen) { size_t len; const char *s = STR(n); int quote = Py_CHARMASK(*s); int fmode = 0; *bytesmode = 0; *rawmode = 0; *result = NULL; *fstr = NULL; if (Py_ISALPHA(quote)) { while (!*bytesmode || !*rawmode) { if (quote == 'b' || quote == 'B') { quote = *++s; *bytesmode = 1; } else if (quote == 'u' || quote == 'U') { quote = *++s; } else if (quote == 'r' || quote == 'R') { quote = *++s; *rawmode = 1; } else if (quote == 'f' || quote == 'F') { quote = *++s; fmode = 1; } else { break; } } } if (fmode && *bytesmode) { PyErr_BadInternalCall(); return -1; } if (quote != '\'' && quote != '\"') { PyErr_BadInternalCall(); return -1; } /* Skip the leading quote char. */ s++; len = strlen(s); if (len > INT_MAX) { PyErr_SetString(PyExc_OverflowError, "string to parse is too long"); return -1; } if (s[--len] != quote) { /* Last quote char must match the first. */ PyErr_BadInternalCall(); return -1; } if (len >= 4 && s[0] == quote && s[1] == quote) { /* A triple quoted string. We've already skipped one quote at the start and one at the end of the string. Now skip the two at the start. */ s += 2; len -= 2; /* And check that the last two match. */ if (s[--len] != quote || s[--len] != quote) { PyErr_BadInternalCall(); return -1; } } if (fmode) { /* Just return the bytes. The caller will parse the resulting string. */ *fstr = s; *fstrlen = len; return 0; } /* Not an f-string. */ /* Avoid invoking escape decoding routines if possible. */ *rawmode = *rawmode || strchr(s, '\\') == NULL; if (*bytesmode) { /* Disallow non-ASCII characters. */ const char *ch; for (ch = s; *ch; ch++) { if (Py_CHARMASK(*ch) >= 0x80) { ast_error(c, n, "bytes can only contain ASCII " "literal characters."); return -1; } } if (*rawmode) *result = PyBytes_FromStringAndSize(s, len); else *result = decode_bytes_with_escapes(c, n, s, len); } else { if (*rawmode) *result = PyUnicode_DecodeUTF8Stateful(s, len, NULL, NULL); else *result = decode_unicode_with_escapes(c, n, s, len); } return *result == NULL ? -1 : 0; } /* Accepts a STRING+ atom, and produces an expr_ty node. Run through each STRING atom, and process it as needed. For bytes, just concatenate them together, and the result will be a Bytes node. For normal strings and f-strings, concatenate them together. The result will be a Str node if there were no f-strings; a FormattedValue node if there's just an f-string (with no leading or trailing literals), or a JoinedStr node if there are multiple f-strings or any literals involved. */ static expr_ty parsestrplus(struct compiling *c, const node *n) { int bytesmode = 0; PyObject *bytes_str = NULL; int i; FstringParser state; FstringParser_Init(&state); for (i = 0; i < NCH(n); i++) { int this_bytesmode; int this_rawmode; PyObject *s; const char *fstr; Py_ssize_t fstrlen = -1; /* Silence a compiler warning. */ REQ(CHILD(n, i), STRING); if (parsestr(c, CHILD(n, i), &this_bytesmode, &this_rawmode, &s, &fstr, &fstrlen) != 0) goto error; /* Check that we're not mixing bytes with unicode. */ if (i != 0 && bytesmode != this_bytesmode) { ast_error(c, n, "cannot mix bytes and nonbytes literals"); /* s is NULL if the current string part is an f-string. */ Py_XDECREF(s); goto error; } bytesmode = this_bytesmode; if (fstr != NULL) { int result; assert(s == NULL && !bytesmode); /* This is an f-string. Parse and concatenate it. */ result = FstringParser_ConcatFstring(&state, &fstr, fstr+fstrlen, this_rawmode, 0, c, n); if (result < 0) goto error; } else { /* A string or byte string. */ assert(s != NULL && fstr == NULL); assert(bytesmode ? PyBytes_CheckExact(s) : PyUnicode_CheckExact(s)); if (bytesmode) { /* For bytes, concat as we go. */ if (i == 0) { /* First time, just remember this value. */ bytes_str = s; } else { PyBytes_ConcatAndDel(&bytes_str, s); if (!bytes_str) goto error; } } else { /* This is a regular string. Concatenate it. */ if (FstringParser_ConcatAndDel(&state, s) < 0) goto error; } } } if (bytesmode) { /* Just return the bytes object and we're done. */ if (PyArena_AddPyObject(c->c_arena, bytes_str) < 0) goto error; return Bytes(bytes_str, LINENO(n), n->n_col_offset, c->c_arena); } /* We're not a bytes string, bytes_str should never have been set. */ assert(bytes_str == NULL); return FstringParser_Finish(&state, c, n); error: Py_XDECREF(bytes_str); FstringParser_Dealloc(&state); return NULL; }
165,440
5,260
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/symtable.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/Python-ast.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/code.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/objimpl.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/setobject.h" #include "third_party/python/Include/structmember.h" #include "third_party/python/Include/symtable.h" /* clang-format off */ /* error strings used for warnings */ #define GLOBAL_AFTER_ASSIGN \ "name '%U' is assigned to before global declaration" #define NONLOCAL_AFTER_ASSIGN \ "name '%U' is assigned to before nonlocal declaration" #define GLOBAL_AFTER_USE \ "name '%U' is used prior to global declaration" #define NONLOCAL_AFTER_USE \ "name '%U' is used prior to nonlocal declaration" #define GLOBAL_ANNOT \ "annotated name '%U' can't be global" #define NONLOCAL_ANNOT \ "annotated name '%U' can't be nonlocal" #define IMPORT_STAR_WARNING "import * only allowed at module level" static PySTEntryObject * ste_new(struct symtable *st, identifier name, _Py_block_ty block, void *key, int lineno, int col_offset) { PySTEntryObject *ste = NULL; PyObject *k = NULL; k = PyLong_FromVoidPtr(key); if (k == NULL) goto fail; ste = PyObject_New(PySTEntryObject, &PySTEntry_Type); if (ste == NULL) { Py_DECREF(k); goto fail; } ste->ste_table = st; ste->ste_id = k; /* ste owns reference to k */ Py_INCREF(name); ste->ste_name = name; ste->ste_symbols = NULL; ste->ste_varnames = NULL; ste->ste_children = NULL; ste->ste_directives = NULL; ste->ste_type = block; ste->ste_nested = 0; ste->ste_free = 0; ste->ste_varargs = 0; ste->ste_varkeywords = 0; ste->ste_opt_lineno = 0; ste->ste_opt_col_offset = 0; ste->ste_tmpname = 0; ste->ste_lineno = lineno; ste->ste_col_offset = col_offset; if (st->st_cur != NULL && (st->st_cur->ste_nested || st->st_cur->ste_type == FunctionBlock)) ste->ste_nested = 1; ste->ste_child_free = 0; ste->ste_generator = 0; ste->ste_coroutine = 0; ste->ste_returns_value = 0; ste->ste_needs_class_closure = 0; ste->ste_symbols = PyDict_New(); ste->ste_varnames = PyList_New(0); ste->ste_children = PyList_New(0); if (ste->ste_symbols == NULL || ste->ste_varnames == NULL || ste->ste_children == NULL) goto fail; if (PyDict_SetItem(st->st_blocks, ste->ste_id, (PyObject *)ste) < 0) goto fail; return ste; fail: Py_XDECREF(ste); return NULL; } static PyObject * ste_repr(PySTEntryObject *ste) { return PyUnicode_FromFormat("<symtable entry %U(%ld), line %d>", ste->ste_name, PyLong_AS_LONG(ste->ste_id), ste->ste_lineno); } static void ste_dealloc(PySTEntryObject *ste) { ste->ste_table = NULL; Py_XDECREF(ste->ste_id); Py_XDECREF(ste->ste_name); Py_XDECREF(ste->ste_symbols); Py_XDECREF(ste->ste_varnames); Py_XDECREF(ste->ste_children); Py_XDECREF(ste->ste_directives); PyObject_Del(ste); } #define OFF(x) offsetof(PySTEntryObject, x) static PyMemberDef ste_memberlist[] = { {"id", T_OBJECT, OFF(ste_id), READONLY}, {"name", T_OBJECT, OFF(ste_name), READONLY}, {"symbols", T_OBJECT, OFF(ste_symbols), READONLY}, {"varnames", T_OBJECT, OFF(ste_varnames), READONLY}, {"children", T_OBJECT, OFF(ste_children), READONLY}, {"nested", T_INT, OFF(ste_nested), READONLY}, {"type", T_INT, OFF(ste_type), READONLY}, {"lineno", T_INT, OFF(ste_lineno), READONLY}, {NULL} }; PyTypeObject PySTEntry_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "symtable entry", sizeof(PySTEntryObject), 0, (destructor)ste_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)ste_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ ste_memberlist, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ }; static int symtable_analyze(struct symtable *st); static int symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block, void *ast, int lineno, int col_offset); static int symtable_exit_block(struct symtable *st, void *ast); static int symtable_visit_stmt(struct symtable *st, stmt_ty s); static int symtable_visit_expr(struct symtable *st, expr_ty s); static int symtable_visit_genexp(struct symtable *st, expr_ty s); static int symtable_visit_listcomp(struct symtable *st, expr_ty s); static int symtable_visit_setcomp(struct symtable *st, expr_ty s); static int symtable_visit_dictcomp(struct symtable *st, expr_ty s); static int symtable_visit_arguments(struct symtable *st, arguments_ty); static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty); static int symtable_visit_alias(struct symtable *st, alias_ty); static int symtable_visit_comprehension(struct symtable *st, comprehension_ty); static int symtable_visit_keyword(struct symtable *st, keyword_ty); static int symtable_visit_slice(struct symtable *st, slice_ty); static int symtable_visit_params(struct symtable *st, asdl_seq *args); static int symtable_visit_argannotations(struct symtable *st, asdl_seq *args); static int symtable_implicit_arg(struct symtable *st, int pos); static int symtable_visit_annotations(struct symtable *st, stmt_ty s, arguments_ty, expr_ty); static int symtable_visit_withitem(struct symtable *st, withitem_ty item); static identifier top = NULL, lambda = NULL, genexpr = NULL, listcomp = NULL, setcomp = NULL, dictcomp = NULL, __class__ = NULL; #define GET_IDENTIFIER(VAR) \ ((VAR) ? (VAR) : ((VAR) = PyUnicode_InternFromString(# VAR))) #define DUPLICATE_ARGUMENT \ "duplicate argument '%U' in function definition" static struct symtable * symtable_new(void) { struct symtable *st; st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable)); if (st == NULL) { PyErr_NoMemory(); return NULL; } st->st_filename = NULL; st->st_blocks = NULL; if ((st->st_stack = PyList_New(0)) == NULL) goto fail; if ((st->st_blocks = PyDict_New()) == NULL) goto fail; st->st_cur = NULL; st->st_private = NULL; return st; fail: PySymtable_Free(st); return NULL; } /* When compiling the use of C stack is probably going to be a lot lighter than when executing Python code but still can overflow and causing a Python crash if not checked (e.g. eval("()"*300000)). Using the current recursion limit for the compiler seems too restrictive (it caused at least one test to fail) so a factor is used to allow deeper recursion when compiling an expression. Using a scaling factor means this should automatically adjust when the recursion limit is adjusted for small or large C stack allocations. */ #define COMPILER_STACK_FRAME_SCALE 3 struct symtable * PySymtable_BuildObject(mod_ty mod, PyObject *filename, PyFutureFeatures *future) { struct symtable *st = symtable_new(); asdl_seq *seq; int i; PyThreadState *tstate; int recursion_limit = Py_GetRecursionLimit(); if (st == NULL) return NULL; if (filename == NULL) { PySymtable_Free(st); return NULL; } Py_INCREF(filename); st->st_filename = filename; st->st_future = future; /* Setup recursion depth check counters */ tstate = PyThreadState_GET(); if (!tstate) { PySymtable_Free(st); return NULL; } /* Be careful here to prevent overflow. */ st->recursion_depth = (tstate->recursion_depth < INT_MAX / COMPILER_STACK_FRAME_SCALE) ? tstate->recursion_depth * COMPILER_STACK_FRAME_SCALE : tstate->recursion_depth; st->recursion_limit = (recursion_limit < INT_MAX / COMPILER_STACK_FRAME_SCALE) ? recursion_limit * COMPILER_STACK_FRAME_SCALE : recursion_limit; /* Make the initial symbol information gathering pass */ if (!GET_IDENTIFIER(top) || !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0, 0)) { PySymtable_Free(st); return NULL; } st->st_top = st->st_cur; switch (mod->kind) { case Module_kind: seq = mod->v.Module.body; for (i = 0; i < asdl_seq_LEN(seq); i++) if (!symtable_visit_stmt(st, (stmt_ty)asdl_seq_GET(seq, i))) goto error; break; case Expression_kind: if (!symtable_visit_expr(st, mod->v.Expression.body)) goto error; break; case Interactive_kind: seq = mod->v.Interactive.body; for (i = 0; i < asdl_seq_LEN(seq); i++) if (!symtable_visit_stmt(st, (stmt_ty)asdl_seq_GET(seq, i))) goto error; break; case Suite_kind: PyErr_SetString(PyExc_RuntimeError, "this compiler does not handle Suites"); goto error; } if (!symtable_exit_block(st, (void *)mod)) { PySymtable_Free(st); return NULL; } /* Make the second symbol analysis pass */ if (symtable_analyze(st)) return st; PySymtable_Free(st); return NULL; error: (void) symtable_exit_block(st, (void *)mod); PySymtable_Free(st); return NULL; } struct symtable * PySymtable_Build(mod_ty mod, const char *filename_str, PyFutureFeatures *future) { PyObject *filename; struct symtable *st; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) return NULL; st = PySymtable_BuildObject(mod, filename, future); Py_DECREF(filename); return st; } void PySymtable_Free(struct symtable *st) { Py_XDECREF(st->st_filename); Py_XDECREF(st->st_blocks); Py_XDECREF(st->st_stack); PyMem_Free((void *)st); } PySTEntryObject * PySymtable_Lookup(struct symtable *st, void *key) { PyObject *k, *v; k = PyLong_FromVoidPtr(key); if (k == NULL) return NULL; v = PyDict_GetItem(st->st_blocks, k); if (v) { assert(PySTEntry_Check(v)); Py_INCREF(v); } else { PyErr_SetString(PyExc_KeyError, "unknown symbol table entry"); } Py_DECREF(k); return (PySTEntryObject *)v; } int PyST_GetScope(PySTEntryObject *ste, PyObject *name) { PyObject *v = PyDict_GetItem(ste->ste_symbols, name); if (!v) return 0; assert(PyLong_Check(v)); return (PyLong_AS_LONG(v) >> SCOPE_OFFSET) & SCOPE_MASK; } static int error_at_directive(PySTEntryObject *ste, PyObject *name) { Py_ssize_t i; PyObject *data; assert(ste->ste_directives); for (i = 0; i < PyList_GET_SIZE(ste->ste_directives); i++) { data = PyList_GET_ITEM(ste->ste_directives, i); assert(PyTuple_CheckExact(data)); assert(PyUnicode_CheckExact(PyTuple_GET_ITEM(data, 0))); if (PyUnicode_Compare(PyTuple_GET_ITEM(data, 0), name) == 0) { PyErr_SyntaxLocationObject(ste->ste_table->st_filename, PyLong_AsLong(PyTuple_GET_ITEM(data, 1)), PyLong_AsLong(PyTuple_GET_ITEM(data, 2))); return 0; } } PyErr_SetString(PyExc_RuntimeError, "BUG: internal directive bookkeeping broken"); return 0; } /* Analyze raw symbol information to determine scope of each name. The next several functions are helpers for symtable_analyze(), which determines whether a name is local, global, or free. In addition, it determines which local variables are cell variables; they provide bindings that are used for free variables in enclosed blocks. There are also two kinds of global variables, implicit and explicit. An explicit global is declared with the global statement. An implicit global is a free variable for which the compiler has found no binding in an enclosing function scope. The implicit global is either a global or a builtin. Python's module and class blocks use the xxx_NAME opcodes to handle these names to implement slightly odd semantics. In such a block, the name is treated as global until it is assigned to; then it is treated as a local. The symbol table requires two passes to determine the scope of each name. The first pass collects raw facts from the AST via the symtable_visit_* functions: the name is a parameter here, the name is used but not defined here, etc. The second pass analyzes these facts during a pass over the PySTEntryObjects created during pass 1. When a function is entered during the second pass, the parent passes the set of all name bindings visible to its children. These bindings are used to determine if non-local variables are free or implicit globals. Names which are explicitly declared nonlocal must exist in this set of visible names - if they do not, a syntax error is raised. After doing the local analysis, it analyzes each of its child blocks using an updated set of name bindings. The children update the free variable set. If a local variable is added to the free variable set by the child, the variable is marked as a cell. The function object being defined must provide runtime storage for the variable that may outlive the function's frame. Cell variables are removed from the free set before the analyze function returns to its parent. During analysis, the names are: symbols: dict mapping from symbol names to flag values (including offset scope values) scopes: dict mapping from symbol names to scope values (no offset) local: set of all symbol names local to the current scope bound: set of all symbol names local to a containing function scope free: set of all symbol names referenced but not bound in child scopes global: set of all symbol names explicitly declared as global */ #define SET_SCOPE(DICT, NAME, I) { \ PyObject *o = PyLong_FromLong(I); \ if (!o) \ return 0; \ if (PyDict_SetItem((DICT), (NAME), o) < 0) { \ Py_DECREF(o); \ return 0; \ } \ Py_DECREF(o); \ } /* Decide on scope of name, given flags. The namespace dictionaries may be modified to record information about the new name. For example, a new global will add an entry to global. A name that was global can be changed to local. */ static int analyze_name(PySTEntryObject *ste, PyObject *scopes, PyObject *name, long flags, PyObject *bound, PyObject *local, PyObject *free, PyObject *global) { if (flags & DEF_GLOBAL) { if (flags & DEF_PARAM) { PyErr_Format(PyExc_SyntaxError, "name '%U' is parameter and global", name); return error_at_directive(ste, name); } if (flags & DEF_NONLOCAL) { PyErr_Format(PyExc_SyntaxError, "name '%U' is nonlocal and global", name); return error_at_directive(ste, name); } SET_SCOPE(scopes, name, GLOBAL_EXPLICIT); if (PySet_Add(global, name) < 0) return 0; if (bound && (PySet_Discard(bound, name) < 0)) return 0; return 1; } if (flags & DEF_NONLOCAL) { if (flags & DEF_PARAM) { PyErr_Format(PyExc_SyntaxError, "name '%U' is parameter and nonlocal", name); return error_at_directive(ste, name); } if (!bound) { PyErr_Format(PyExc_SyntaxError, "nonlocal declaration not allowed at module level"); return error_at_directive(ste, name); } if (!PySet_Contains(bound, name)) { PyErr_Format(PyExc_SyntaxError, "no binding for nonlocal '%U' found", name); return error_at_directive(ste, name); } SET_SCOPE(scopes, name, FREE); ste->ste_free = 1; return PySet_Add(free, name) >= 0; } if (flags & DEF_BOUND) { SET_SCOPE(scopes, name, LOCAL); if (PySet_Add(local, name) < 0) return 0; if (PySet_Discard(global, name) < 0) return 0; return 1; } /* If an enclosing block has a binding for this name, it is a free variable rather than a global variable. Note that having a non-NULL bound implies that the block is nested. */ if (bound && PySet_Contains(bound, name)) { SET_SCOPE(scopes, name, FREE); ste->ste_free = 1; return PySet_Add(free, name) >= 0; } /* If a parent has a global statement, then call it global explicit? It could also be global implicit. */ if (global && PySet_Contains(global, name)) { SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); return 1; } if (ste->ste_nested) ste->ste_free = 1; SET_SCOPE(scopes, name, GLOBAL_IMPLICIT); return 1; } #undef SET_SCOPE /* If a name is defined in free and also in locals, then this block provides the binding for the free variable. The name should be marked CELL in this block and removed from the free list. Note that the current block's free variables are included in free. That's safe because no name can be free and local in the same scope. */ static int analyze_cells(PyObject *scopes, PyObject *free) { PyObject *name, *v, *v_cell; int success = 0; Py_ssize_t pos = 0; v_cell = PyLong_FromLong(CELL); if (!v_cell) return 0; while (PyDict_Next(scopes, &pos, &name, &v)) { long scope; assert(PyLong_Check(v)); scope = PyLong_AS_LONG(v); if (scope != LOCAL) continue; if (!PySet_Contains(free, name)) continue; /* Replace LOCAL with CELL for this name, and remove from free. It is safe to replace the value of name in the dict, because it will not cause a resize. */ if (PyDict_SetItem(scopes, name, v_cell) < 0) goto error; if (PySet_Discard(free, name) < 0) goto error; } success = 1; error: Py_DECREF(v_cell); return success; } static int drop_class_free(PySTEntryObject *ste, PyObject *free) { int res; if (!GET_IDENTIFIER(__class__)) return 0; res = PySet_Discard(free, __class__); if (res < 0) return 0; if (res) ste->ste_needs_class_closure = 1; return 1; } /* Enter the final scope information into the ste_symbols dict. * * All arguments are dicts. Modifies symbols, others are read-only. */ static int update_symbols(PyObject *symbols, PyObject *scopes, PyObject *bound, PyObject *free, int classflag) { PyObject *name = NULL, *itr = NULL; PyObject *v = NULL, *v_scope = NULL, *v_new = NULL, *v_free = NULL; Py_ssize_t pos = 0; /* Update scope information for all symbols in this scope */ while (PyDict_Next(symbols, &pos, &name, &v)) { long scope, flags; assert(PyLong_Check(v)); flags = PyLong_AS_LONG(v); v_scope = PyDict_GetItem(scopes, name); assert(v_scope && PyLong_Check(v_scope)); scope = PyLong_AS_LONG(v_scope); flags |= (scope << SCOPE_OFFSET); v_new = PyLong_FromLong(flags); if (!v_new) return 0; if (PyDict_SetItem(symbols, name, v_new) < 0) { Py_DECREF(v_new); return 0; } Py_DECREF(v_new); } /* Record not yet resolved free variables from children (if any) */ v_free = PyLong_FromLong(FREE << SCOPE_OFFSET); if (!v_free) return 0; itr = PyObject_GetIter(free); if (itr == NULL) { Py_DECREF(v_free); return 0; } while ((name = PyIter_Next(itr))) { v = PyDict_GetItem(symbols, name); /* Handle symbol that already exists in this scope */ if (v) { /* Handle a free variable in a method of the class that has the same name as a local or global in the class scope. */ if (classflag && PyLong_AS_LONG(v) & (DEF_BOUND | DEF_GLOBAL)) { long flags = PyLong_AS_LONG(v) | DEF_FREE_CLASS; v_new = PyLong_FromLong(flags); if (!v_new) { goto error; } if (PyDict_SetItem(symbols, name, v_new) < 0) { Py_DECREF(v_new); goto error; } Py_DECREF(v_new); } /* It's a cell, or already free in this scope */ Py_DECREF(name); continue; } /* Handle global symbol */ if (bound && !PySet_Contains(bound, name)) { Py_DECREF(name); continue; /* it's a global */ } /* Propagate new free symbol up the lexical stack */ if (PyDict_SetItem(symbols, name, v_free) < 0) { goto error; } Py_DECREF(name); } Py_DECREF(itr); Py_DECREF(v_free); return 1; error: Py_XDECREF(v_free); Py_XDECREF(itr); Py_XDECREF(name); return 0; } /* Make final symbol table decisions for block of ste. Arguments: ste -- current symtable entry (input/output) bound -- set of variables bound in enclosing scopes (input). bound is NULL for module blocks. free -- set of free variables in enclosed scopes (output) globals -- set of declared global variables in enclosing scopes (input) The implementation uses two mutually recursive functions, analyze_block() and analyze_child_block(). analyze_block() is responsible for analyzing the individual names defined in a block. analyze_child_block() prepares temporary namespace dictionaries used to evaluated nested blocks. The two functions exist because a child block should see the name bindings of its enclosing blocks, but those bindings should not propagate back to a parent block. */ static int analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, PyObject *global, PyObject* child_free); static int analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free, PyObject *global) { PyObject *name, *v, *local = NULL, *scopes = NULL, *newbound = NULL; PyObject *newglobal = NULL, *newfree = NULL, *allfree = NULL; PyObject *temp; int i, success = 0; Py_ssize_t pos = 0; local = PySet_New(NULL); /* collect new names bound in block */ if (!local) goto error; scopes = PyDict_New(); /* collect scopes defined for each name */ if (!scopes) goto error; /* Allocate new global and bound variable dictionaries. These dictionaries hold the names visible in nested blocks. For ClassBlocks, the bound and global names are initialized before analyzing names, because class bindings aren't visible in methods. For other blocks, they are initialized after names are analyzed. */ /* TODO(jhylton): Package these dicts in a struct so that we can write reasonable helper functions? */ newglobal = PySet_New(NULL); if (!newglobal) goto error; newfree = PySet_New(NULL); if (!newfree) goto error; newbound = PySet_New(NULL); if (!newbound) goto error; /* Class namespace has no effect on names visible in nested functions, so populate the global and bound sets to be passed to child blocks before analyzing this one. */ if (ste->ste_type == ClassBlock) { /* Pass down known globals */ temp = PyNumber_InPlaceOr(newglobal, global); if (!temp) goto error; Py_DECREF(temp); /* Pass down previously bound symbols */ if (bound) { temp = PyNumber_InPlaceOr(newbound, bound); if (!temp) goto error; Py_DECREF(temp); } } while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) { long flags = PyLong_AS_LONG(v); if (!analyze_name(ste, scopes, name, flags, bound, local, free, global)) goto error; } /* Populate global and bound sets to be passed to children. */ if (ste->ste_type != ClassBlock) { /* Add function locals to bound set */ if (ste->ste_type == FunctionBlock) { temp = PyNumber_InPlaceOr(newbound, local); if (!temp) goto error; Py_DECREF(temp); } /* Pass down previously bound symbols */ if (bound) { temp = PyNumber_InPlaceOr(newbound, bound); if (!temp) goto error; Py_DECREF(temp); } /* Pass down known globals */ temp = PyNumber_InPlaceOr(newglobal, global); if (!temp) goto error; Py_DECREF(temp); } else { /* Special-case __class__ */ if (!GET_IDENTIFIER(__class__)) goto error; if (PySet_Add(newbound, __class__) < 0) goto error; } /* Recursively call analyze_child_block() on each child block. newbound, newglobal now contain the names visible in nested blocks. The free variables in the children will be collected in allfree. */ allfree = PySet_New(NULL); if (!allfree) goto error; for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) { PyObject *c = PyList_GET_ITEM(ste->ste_children, i); PySTEntryObject* entry; assert(c && PySTEntry_Check(c)); entry = (PySTEntryObject*)c; if (!analyze_child_block(entry, newbound, newfree, newglobal, allfree)) goto error; /* Check if any children have free variables */ if (entry->ste_free || entry->ste_child_free) ste->ste_child_free = 1; } temp = PyNumber_InPlaceOr(newfree, allfree); if (!temp) goto error; Py_DECREF(temp); /* Check if any local variables must be converted to cell variables */ if (ste->ste_type == FunctionBlock && !analyze_cells(scopes, newfree)) goto error; else if (ste->ste_type == ClassBlock && !drop_class_free(ste, newfree)) goto error; /* Records the results of the analysis in the symbol table entry */ if (!update_symbols(ste->ste_symbols, scopes, bound, newfree, ste->ste_type == ClassBlock)) goto error; temp = PyNumber_InPlaceOr(free, newfree); if (!temp) goto error; Py_DECREF(temp); success = 1; error: Py_XDECREF(scopes); Py_XDECREF(local); Py_XDECREF(newbound); Py_XDECREF(newglobal); Py_XDECREF(newfree); Py_XDECREF(allfree); if (!success) assert(PyErr_Occurred()); return success; } static int analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free, PyObject *global, PyObject* child_free) { PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL; PyObject *temp; /* Copy the bound and global dictionaries. These dictionaries are used by all blocks enclosed by the current block. The analyze_block() call modifies these dictionaries. */ temp_bound = PySet_New(bound); if (!temp_bound) goto error; temp_free = PySet_New(free); if (!temp_free) goto error; temp_global = PySet_New(global); if (!temp_global) goto error; if (!analyze_block(entry, temp_bound, temp_free, temp_global)) goto error; temp = PyNumber_InPlaceOr(child_free, temp_free); if (!temp) goto error; Py_DECREF(temp); Py_DECREF(temp_bound); Py_DECREF(temp_free); Py_DECREF(temp_global); return 1; error: Py_XDECREF(temp_bound); Py_XDECREF(temp_free); Py_XDECREF(temp_global); return 0; } static int symtable_analyze(struct symtable *st) { PyObject *free, *global; int r; free = PySet_New(NULL); if (!free) return 0; global = PySet_New(NULL); if (!global) { Py_DECREF(free); return 0; } r = analyze_block(st->st_top, NULL, free, global); Py_DECREF(free); Py_DECREF(global); return r; } /* symtable_enter_block() gets a reference via ste_new. This reference is released when the block is exited, via the DECREF in symtable_exit_block(). */ static int symtable_exit_block(struct symtable *st, void *ast) { Py_ssize_t size; st->st_cur = NULL; size = PyList_GET_SIZE(st->st_stack); if (size) { if (PyList_SetSlice(st->st_stack, size - 1, size, NULL) < 0) return 0; if (--size) st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack, size - 1); } return 1; } static int symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block, void *ast, int lineno, int col_offset) { PySTEntryObject *prev = NULL, *ste; ste = ste_new(st, name, block, ast, lineno, col_offset); if (ste == NULL) return 0; if (PyList_Append(st->st_stack, (PyObject *)ste) < 0) { Py_DECREF(ste); return 0; } prev = st->st_cur; /* The entry is owned by the stack. Borrow it for st_cur. */ Py_DECREF(ste); st->st_cur = ste; if (block == ModuleBlock) st->st_global = st->st_cur->ste_symbols; if (prev) { if (PyList_Append(prev->ste_children, (PyObject *)ste) < 0) { return 0; } } return 1; } static long symtable_lookup(struct symtable *st, PyObject *name) { PyObject *o; PyObject *mangled = _Py_Mangle(st->st_private, name); if (!mangled) return 0; o = PyDict_GetItem(st->st_cur->ste_symbols, mangled); Py_DECREF(mangled); if (!o) return 0; return PyLong_AsLong(o); } static int symtable_add_def(struct symtable *st, PyObject *name, int flag) { PyObject *o; PyObject *dict; long val; PyObject *mangled = _Py_Mangle(st->st_private, name); if (!mangled) return 0; dict = st->st_cur->ste_symbols; if ((o = PyDict_GetItem(dict, mangled))) { val = PyLong_AS_LONG(o); if ((flag & DEF_PARAM) && (val & DEF_PARAM)) { /* Is it better to use 'mangled' or 'name' here? */ PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT, name); PyErr_SyntaxLocationObject(st->st_filename, st->st_cur->ste_lineno, st->st_cur->ste_col_offset); goto error; } val |= flag; } else val = flag; o = PyLong_FromLong(val); if (o == NULL) goto error; if (PyDict_SetItem(dict, mangled, o) < 0) { Py_DECREF(o); goto error; } Py_DECREF(o); if (flag & DEF_PARAM) { if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0) goto error; } else if (flag & DEF_GLOBAL) { /* XXX need to update DEF_GLOBAL for other flags too; perhaps only DEF_FREE_GLOBAL */ val = flag; if ((o = PyDict_GetItem(st->st_global, mangled))) { val |= PyLong_AS_LONG(o); } o = PyLong_FromLong(val); if (o == NULL) goto error; if (PyDict_SetItem(st->st_global, mangled, o) < 0) { Py_DECREF(o); goto error; } Py_DECREF(o); } Py_DECREF(mangled); return 1; error: Py_DECREF(mangled); return 0; } /* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument. They use the ASDL name to synthesize the name of the C type and the visit function. VISIT_SEQ_TAIL permits the start of an ASDL sequence to be skipped, which is useful if the first node in the sequence requires special treatment. VISIT_QUIT macro returns the specified value exiting from the function but first adjusts current recursion counter depth. */ #define VISIT_QUIT(ST, X) \ return --(ST)->recursion_depth,(X) #define VISIT(ST, TYPE, V) \ if (!symtable_visit_ ## TYPE((ST), (V))) \ VISIT_QUIT((ST), 0); #define VISIT_SEQ(ST, TYPE, SEQ) { \ int i; \ asdl_seq *seq = (SEQ); /* avoid variable capture */ \ for (i = 0; i < asdl_seq_LEN(seq); i++) { \ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ if (!symtable_visit_ ## TYPE((ST), elt)) \ VISIT_QUIT((ST), 0); \ } \ } #define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) { \ int i; \ asdl_seq *seq = (SEQ); /* avoid variable capture */ \ for (i = (START); i < asdl_seq_LEN(seq); i++) { \ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ if (!symtable_visit_ ## TYPE((ST), elt)) \ VISIT_QUIT((ST), 0); \ } \ } #define VISIT_SEQ_WITH_NULL(ST, TYPE, SEQ) { \ int i = 0; \ asdl_seq *seq = (SEQ); /* avoid variable capture */ \ for (i = 0; i < asdl_seq_LEN(seq); i++) { \ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \ if (!elt) continue; /* can be NULL */ \ if (!symtable_visit_ ## TYPE((ST), elt)) \ VISIT_QUIT((ST), 0); \ } \ } static int symtable_new_tmpname(struct symtable *st) { char tmpname[256]; identifier tmp; PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]", ++st->st_cur->ste_tmpname); tmp = PyUnicode_InternFromString(tmpname); if (!tmp) return 0; if (!symtable_add_def(st, tmp, DEF_LOCAL)) return 0; Py_DECREF(tmp); return 1; } static int symtable_record_directive(struct symtable *st, identifier name, stmt_ty s) { PyObject *data, *mangled; int res; if (!st->st_cur->ste_directives) { st->st_cur->ste_directives = PyList_New(0); if (!st->st_cur->ste_directives) return 0; } mangled = _Py_Mangle(st->st_private, name); if (!mangled) return 0; data = Py_BuildValue("(Nii)", mangled, s->lineno, s->col_offset); if (!data) return 0; res = PyList_Append(st->st_cur->ste_directives, data); Py_DECREF(data); return res == 0; } static int symtable_visit_stmt(struct symtable *st, stmt_ty s) { if (++st->recursion_depth > st->recursion_limit) { PyErr_SetString(PyExc_RecursionError, "maximum recursion depth exceeded during compilation"); VISIT_QUIT(st, 0); } switch (s->kind) { case FunctionDef_kind: if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL)) VISIT_QUIT(st, 0); if (s->v.FunctionDef.args->defaults) VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults); if (s->v.FunctionDef.args->kw_defaults) VISIT_SEQ_WITH_NULL(st, expr, s->v.FunctionDef.args->kw_defaults); if (!symtable_visit_annotations(st, s, s->v.FunctionDef.args, s->v.FunctionDef.returns)) VISIT_QUIT(st, 0); if (s->v.FunctionDef.decorator_list) VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list); if (!symtable_enter_block(st, s->v.FunctionDef.name, FunctionBlock, (void *)s, s->lineno, s->col_offset)) VISIT_QUIT(st, 0); VISIT(st, arguments, s->v.FunctionDef.args); VISIT_SEQ(st, stmt, s->v.FunctionDef.body); if (!symtable_exit_block(st, s)) VISIT_QUIT(st, 0); break; case ClassDef_kind: { PyObject *tmp; if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL)) VISIT_QUIT(st, 0); VISIT_SEQ(st, expr, s->v.ClassDef.bases); VISIT_SEQ(st, keyword, s->v.ClassDef.keywords); if (s->v.ClassDef.decorator_list) VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list); if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock, (void *)s, s->lineno, s->col_offset)) VISIT_QUIT(st, 0); tmp = st->st_private; st->st_private = s->v.ClassDef.name; VISIT_SEQ(st, stmt, s->v.ClassDef.body); st->st_private = tmp; if (!symtable_exit_block(st, s)) VISIT_QUIT(st, 0); break; } case Return_kind: if (s->v.Return.value) { VISIT(st, expr, s->v.Return.value); st->st_cur->ste_returns_value = 1; } break; case Delete_kind: VISIT_SEQ(st, expr, s->v.Delete.targets); break; case Assign_kind: VISIT_SEQ(st, expr, s->v.Assign.targets); VISIT(st, expr, s->v.Assign.value); break; case AnnAssign_kind: if (s->v.AnnAssign.target->kind == Name_kind) { expr_ty e_name = s->v.AnnAssign.target; long cur = symtable_lookup(st, e_name->v.Name.id); if (cur < 0) { VISIT_QUIT(st, 0); } if ((cur & (DEF_GLOBAL | DEF_NONLOCAL)) && s->v.AnnAssign.simple) { PyErr_Format(PyExc_SyntaxError, cur & DEF_GLOBAL ? GLOBAL_ANNOT : NONLOCAL_ANNOT, e_name->v.Name.id); PyErr_SyntaxLocationObject(st->st_filename, s->lineno, s->col_offset); VISIT_QUIT(st, 0); } if (s->v.AnnAssign.simple && !symtable_add_def(st, e_name->v.Name.id, DEF_ANNOT | DEF_LOCAL)) { VISIT_QUIT(st, 0); } else { if (s->v.AnnAssign.value && !symtable_add_def(st, e_name->v.Name.id, DEF_LOCAL)) { VISIT_QUIT(st, 0); } } } else { VISIT(st, expr, s->v.AnnAssign.target); } VISIT(st, expr, s->v.AnnAssign.annotation); if (s->v.AnnAssign.value) { VISIT(st, expr, s->v.AnnAssign.value); } break; case AugAssign_kind: VISIT(st, expr, s->v.AugAssign.target); VISIT(st, expr, s->v.AugAssign.value); break; case For_kind: VISIT(st, expr, s->v.For.target); VISIT(st, expr, s->v.For.iter); VISIT_SEQ(st, stmt, s->v.For.body); if (s->v.For.orelse) VISIT_SEQ(st, stmt, s->v.For.orelse); break; case While_kind: VISIT(st, expr, s->v.While.test); VISIT_SEQ(st, stmt, s->v.While.body); if (s->v.While.orelse) VISIT_SEQ(st, stmt, s->v.While.orelse); break; case If_kind: /* XXX if 0: and lookup_yield() hacks */ VISIT(st, expr, s->v.If.test); VISIT_SEQ(st, stmt, s->v.If.body); if (s->v.If.orelse) VISIT_SEQ(st, stmt, s->v.If.orelse); break; case Raise_kind: if (s->v.Raise.exc) { VISIT(st, expr, s->v.Raise.exc); if (s->v.Raise.cause) { VISIT(st, expr, s->v.Raise.cause); } } break; case Try_kind: VISIT_SEQ(st, stmt, s->v.Try.body); VISIT_SEQ(st, stmt, s->v.Try.orelse); VISIT_SEQ(st, excepthandler, s->v.Try.handlers); VISIT_SEQ(st, stmt, s->v.Try.finalbody); break; case Assert_kind: VISIT(st, expr, s->v.Assert.test); if (s->v.Assert.msg) VISIT(st, expr, s->v.Assert.msg); break; case Import_kind: VISIT_SEQ(st, alias, s->v.Import.names); break; case ImportFrom_kind: VISIT_SEQ(st, alias, s->v.ImportFrom.names); break; case Global_kind: { int i; asdl_seq *seq = s->v.Global.names; for (i = 0; i < asdl_seq_LEN(seq); i++) { identifier name = (identifier)asdl_seq_GET(seq, i); long cur = symtable_lookup(st, name); if (cur < 0) VISIT_QUIT(st, 0); if (cur & (DEF_LOCAL | USE | DEF_ANNOT)) { char* msg; if (cur & USE) { msg = GLOBAL_AFTER_USE; } else if (cur & DEF_ANNOT) { msg = GLOBAL_ANNOT; } else { /* DEF_LOCAL */ msg = GLOBAL_AFTER_ASSIGN; } PyErr_Format(PyExc_SyntaxError, msg, name); PyErr_SyntaxLocationObject(st->st_filename, s->lineno, s->col_offset); VISIT_QUIT(st, 0); } if (!symtable_add_def(st, name, DEF_GLOBAL)) VISIT_QUIT(st, 0); if (!symtable_record_directive(st, name, s)) VISIT_QUIT(st, 0); } break; } case Nonlocal_kind: { int i; asdl_seq *seq = s->v.Nonlocal.names; for (i = 0; i < asdl_seq_LEN(seq); i++) { identifier name = (identifier)asdl_seq_GET(seq, i); long cur = symtable_lookup(st, name); if (cur < 0) VISIT_QUIT(st, 0); if (cur & (DEF_LOCAL | USE | DEF_ANNOT)) { char* msg; if (cur & USE) { msg = NONLOCAL_AFTER_USE; } else if (cur & DEF_ANNOT) { msg = NONLOCAL_ANNOT; } else { /* DEF_LOCAL */ msg = NONLOCAL_AFTER_ASSIGN; } PyErr_Format(PyExc_SyntaxError, msg, name); PyErr_SyntaxLocationObject(st->st_filename, s->lineno, s->col_offset); VISIT_QUIT(st, 0); } if (!symtable_add_def(st, name, DEF_NONLOCAL)) VISIT_QUIT(st, 0); if (!symtable_record_directive(st, name, s)) VISIT_QUIT(st, 0); } break; } case Expr_kind: VISIT(st, expr, s->v.Expr.value); break; case Pass_kind: case Break_kind: case Continue_kind: /* nothing to do here */ break; case With_kind: VISIT_SEQ(st, withitem, s->v.With.items); VISIT_SEQ(st, stmt, s->v.With.body); break; case AsyncFunctionDef_kind: if (!symtable_add_def(st, s->v.AsyncFunctionDef.name, DEF_LOCAL)) VISIT_QUIT(st, 0); if (s->v.AsyncFunctionDef.args->defaults) VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.args->defaults); if (s->v.AsyncFunctionDef.args->kw_defaults) VISIT_SEQ_WITH_NULL(st, expr, s->v.AsyncFunctionDef.args->kw_defaults); if (!symtable_visit_annotations(st, s, s->v.AsyncFunctionDef.args, s->v.AsyncFunctionDef.returns)) VISIT_QUIT(st, 0); if (s->v.AsyncFunctionDef.decorator_list) VISIT_SEQ(st, expr, s->v.AsyncFunctionDef.decorator_list); if (!symtable_enter_block(st, s->v.AsyncFunctionDef.name, FunctionBlock, (void *)s, s->lineno, s->col_offset)) VISIT_QUIT(st, 0); st->st_cur->ste_coroutine = 1; VISIT(st, arguments, s->v.AsyncFunctionDef.args); VISIT_SEQ(st, stmt, s->v.AsyncFunctionDef.body); if (!symtable_exit_block(st, s)) VISIT_QUIT(st, 0); break; case AsyncWith_kind: VISIT_SEQ(st, withitem, s->v.AsyncWith.items); VISIT_SEQ(st, stmt, s->v.AsyncWith.body); break; case AsyncFor_kind: VISIT(st, expr, s->v.AsyncFor.target); VISIT(st, expr, s->v.AsyncFor.iter); VISIT_SEQ(st, stmt, s->v.AsyncFor.body); if (s->v.AsyncFor.orelse) VISIT_SEQ(st, stmt, s->v.AsyncFor.orelse); break; } VISIT_QUIT(st, 1); } static int symtable_visit_expr(struct symtable *st, expr_ty e) { if (++st->recursion_depth > st->recursion_limit) { PyErr_SetString(PyExc_RecursionError, "maximum recursion depth exceeded during compilation"); VISIT_QUIT(st, 0); } switch (e->kind) { case BoolOp_kind: VISIT_SEQ(st, expr, e->v.BoolOp.values); break; case BinOp_kind: VISIT(st, expr, e->v.BinOp.left); VISIT(st, expr, e->v.BinOp.right); break; case UnaryOp_kind: VISIT(st, expr, e->v.UnaryOp.operand); break; case Lambda_kind: { if (!GET_IDENTIFIER(lambda)) VISIT_QUIT(st, 0); if (e->v.Lambda.args->defaults) VISIT_SEQ(st, expr, e->v.Lambda.args->defaults); if (e->v.Lambda.args->kw_defaults) VISIT_SEQ_WITH_NULL(st, expr, e->v.Lambda.args->kw_defaults); if (!symtable_enter_block(st, lambda, FunctionBlock, (void *)e, e->lineno, e->col_offset)) VISIT_QUIT(st, 0); VISIT(st, arguments, e->v.Lambda.args); VISIT(st, expr, e->v.Lambda.body); if (!symtable_exit_block(st, (void *)e)) VISIT_QUIT(st, 0); break; } case IfExp_kind: VISIT(st, expr, e->v.IfExp.test); VISIT(st, expr, e->v.IfExp.body); VISIT(st, expr, e->v.IfExp.orelse); break; case Dict_kind: VISIT_SEQ_WITH_NULL(st, expr, e->v.Dict.keys); VISIT_SEQ(st, expr, e->v.Dict.values); break; case Set_kind: VISIT_SEQ(st, expr, e->v.Set.elts); break; case GeneratorExp_kind: if (!symtable_visit_genexp(st, e)) VISIT_QUIT(st, 0); break; case ListComp_kind: if (!symtable_visit_listcomp(st, e)) VISIT_QUIT(st, 0); break; case SetComp_kind: if (!symtable_visit_setcomp(st, e)) VISIT_QUIT(st, 0); break; case DictComp_kind: if (!symtable_visit_dictcomp(st, e)) VISIT_QUIT(st, 0); break; case Yield_kind: if (e->v.Yield.value) VISIT(st, expr, e->v.Yield.value); st->st_cur->ste_generator = 1; break; case YieldFrom_kind: VISIT(st, expr, e->v.YieldFrom.value); st->st_cur->ste_generator = 1; break; case Await_kind: VISIT(st, expr, e->v.Await.value); st->st_cur->ste_coroutine = 1; break; case Compare_kind: VISIT(st, expr, e->v.Compare.left); VISIT_SEQ(st, expr, e->v.Compare.comparators); break; case Call_kind: VISIT(st, expr, e->v.Call.func); VISIT_SEQ(st, expr, e->v.Call.args); VISIT_SEQ_WITH_NULL(st, keyword, e->v.Call.keywords); break; case FormattedValue_kind: VISIT(st, expr, e->v.FormattedValue.value); if (e->v.FormattedValue.format_spec) VISIT(st, expr, e->v.FormattedValue.format_spec); break; case JoinedStr_kind: VISIT_SEQ(st, expr, e->v.JoinedStr.values); break; case Constant_kind: case Num_kind: case Str_kind: case Bytes_kind: case Ellipsis_kind: case NameConstant_kind: /* Nothing to do here. */ break; /* The following exprs can be assignment targets. */ case Attribute_kind: VISIT(st, expr, e->v.Attribute.value); break; case Subscript_kind: VISIT(st, expr, e->v.Subscript.value); VISIT(st, slice, e->v.Subscript.slice); break; case Starred_kind: VISIT(st, expr, e->v.Starred.value); break; case Name_kind: if (!symtable_add_def(st, e->v.Name.id, e->v.Name.ctx == Load ? USE : DEF_LOCAL)) VISIT_QUIT(st, 0); /* Special-case super: it counts as a use of __class__ */ if (e->v.Name.ctx == Load && st->st_cur->ste_type == FunctionBlock && _PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) { if (!GET_IDENTIFIER(__class__) || !symtable_add_def(st, __class__, USE)) VISIT_QUIT(st, 0); } break; /* child nodes of List and Tuple will have expr_context set */ case List_kind: VISIT_SEQ(st, expr, e->v.List.elts); break; case Tuple_kind: VISIT_SEQ(st, expr, e->v.Tuple.elts); break; } VISIT_QUIT(st, 1); } static int symtable_implicit_arg(struct symtable *st, int pos) { PyObject *id = PyUnicode_FromFormat(".%d", pos); if (id == NULL) return 0; if (!symtable_add_def(st, id, DEF_PARAM)) { Py_DECREF(id); return 0; } Py_DECREF(id); return 1; } static int symtable_visit_params(struct symtable *st, asdl_seq *args) { int i; if (!args) return -1; for (i = 0; i < asdl_seq_LEN(args); i++) { arg_ty arg = (arg_ty)asdl_seq_GET(args, i); if (!symtable_add_def(st, arg->arg, DEF_PARAM)) return 0; } return 1; } static int symtable_visit_argannotations(struct symtable *st, asdl_seq *args) { int i; if (!args) return -1; for (i = 0; i < asdl_seq_LEN(args); i++) { arg_ty arg = (arg_ty)asdl_seq_GET(args, i); if (arg->annotation) VISIT(st, expr, arg->annotation); } return 1; } static int symtable_visit_annotations(struct symtable *st, stmt_ty s, arguments_ty a, expr_ty returns) { if (a->args && !symtable_visit_argannotations(st, a->args)) return 0; if (a->vararg && a->vararg->annotation) VISIT(st, expr, a->vararg->annotation); if (a->kwarg && a->kwarg->annotation) VISIT(st, expr, a->kwarg->annotation); if (a->kwonlyargs && !symtable_visit_argannotations(st, a->kwonlyargs)) return 0; if (returns) VISIT(st, expr, returns); return 1; } static int symtable_visit_arguments(struct symtable *st, arguments_ty a) { /* skip default arguments inside function block XXX should ast be different? */ if (a->args && !symtable_visit_params(st, a->args)) return 0; if (a->kwonlyargs && !symtable_visit_params(st, a->kwonlyargs)) return 0; if (a->vararg) { if (!symtable_add_def(st, a->vararg->arg, DEF_PARAM)) return 0; st->st_cur->ste_varargs = 1; } if (a->kwarg) { if (!symtable_add_def(st, a->kwarg->arg, DEF_PARAM)) return 0; st->st_cur->ste_varkeywords = 1; } return 1; } static int symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh) { if (eh->v.ExceptHandler.type) VISIT(st, expr, eh->v.ExceptHandler.type); if (eh->v.ExceptHandler.name) if (!symtable_add_def(st, eh->v.ExceptHandler.name, DEF_LOCAL)) return 0; VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body); return 1; } static int symtable_visit_withitem(struct symtable *st, withitem_ty item) { VISIT(st, expr, item->context_expr); if (item->optional_vars) { VISIT(st, expr, item->optional_vars); } return 1; } static int symtable_visit_alias(struct symtable *st, alias_ty a) { /* Compute store_name, the name actually bound by the import operation. It is different than a->name when a->name is a dotted package name (e.g. spam.eggs) */ PyObject *store_name; PyObject *name = (a->asname == NULL) ? a->name : a->asname; Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, PyUnicode_GET_LENGTH(name), 1); if (dot != -1) { store_name = PyUnicode_Substring(name, 0, dot); if (!store_name) return 0; } else { store_name = name; Py_INCREF(store_name); } if (!_PyUnicode_EqualToASCIIString(name, "*")) { int r = symtable_add_def(st, store_name, DEF_IMPORT); Py_DECREF(store_name); return r; } else { if (st->st_cur->ste_type != ModuleBlock) { int lineno = st->st_cur->ste_lineno; int col_offset = st->st_cur->ste_col_offset; PyErr_SetString(PyExc_SyntaxError, IMPORT_STAR_WARNING); PyErr_SyntaxLocationObject(st->st_filename, lineno, col_offset); Py_DECREF(store_name); return 0; } Py_DECREF(store_name); return 1; } } static int symtable_visit_comprehension(struct symtable *st, comprehension_ty lc) { VISIT(st, expr, lc->target); VISIT(st, expr, lc->iter); VISIT_SEQ(st, expr, lc->ifs); if (lc->is_async) { st->st_cur->ste_coroutine = 1; } return 1; } static int symtable_visit_keyword(struct symtable *st, keyword_ty k) { VISIT(st, expr, k->value); return 1; } static int symtable_visit_slice(struct symtable *st, slice_ty s) { switch (s->kind) { case Slice_kind: if (s->v.Slice.lower) VISIT(st, expr, s->v.Slice.lower) if (s->v.Slice.upper) VISIT(st, expr, s->v.Slice.upper) if (s->v.Slice.step) VISIT(st, expr, s->v.Slice.step) break; case ExtSlice_kind: VISIT_SEQ(st, slice, s->v.ExtSlice.dims) break; case Index_kind: VISIT(st, expr, s->v.Index.value) break; } return 1; } static int symtable_handle_comprehension(struct symtable *st, expr_ty e, identifier scope_name, asdl_seq *generators, expr_ty elt, expr_ty value) { int is_generator = (e->kind == GeneratorExp_kind); int needs_tmp = !is_generator; comprehension_ty outermost = ((comprehension_ty) asdl_seq_GET(generators, 0)); /* Outermost iterator is evaluated in current scope */ VISIT(st, expr, outermost->iter); /* Create comprehension scope for the rest */ if (!scope_name || !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, e->lineno, e->col_offset)) { return 0; } st->st_cur->ste_generator = is_generator; if (outermost->is_async) { st->st_cur->ste_coroutine = 1; } /* Outermost iter is received as an argument */ if (!symtable_implicit_arg(st, 0)) { symtable_exit_block(st, (void *)e); return 0; } /* Allocate temporary name if needed */ if (needs_tmp && !symtable_new_tmpname(st)) { symtable_exit_block(st, (void *)e); return 0; } VISIT(st, expr, outermost->target); VISIT_SEQ(st, expr, outermost->ifs); VISIT_SEQ_TAIL(st, comprehension, generators, 1); if (value) VISIT(st, expr, value); VISIT(st, expr, elt); return symtable_exit_block(st, (void *)e); } static int symtable_visit_genexp(struct symtable *st, expr_ty e) { return symtable_handle_comprehension(st, e, GET_IDENTIFIER(genexpr), e->v.GeneratorExp.generators, e->v.GeneratorExp.elt, NULL); } static int symtable_visit_listcomp(struct symtable *st, expr_ty e) { return symtable_handle_comprehension(st, e, GET_IDENTIFIER(listcomp), e->v.ListComp.generators, e->v.ListComp.elt, NULL); } static int symtable_visit_setcomp(struct symtable *st, expr_ty e) { return symtable_handle_comprehension(st, e, GET_IDENTIFIER(setcomp), e->v.SetComp.generators, e->v.SetComp.elt, NULL); } static int symtable_visit_dictcomp(struct symtable *st, expr_ty e) { return symtable_handle_comprehension(st, e, GET_IDENTIFIER(dictcomp), e->v.DictComp.generators, e->v.DictComp.key, e->v.DictComp.value); }
59,615
1,809
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pytime.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/weirdtypes.h" #include "libc/math.h" #include "libc/nt/synchronization.h" #include "libc/sysv/consts/clock.h" #include "libc/time/time.h" #include "third_party/python/Include/floatobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymath.h" #include "third_party/python/Include/pytime.h" /* clang-format off */ #define _PyTime_check_mul_overflow(a, b) \ (assert(b > 0), \ (_PyTime_t)(a) < _PyTime_MIN / (_PyTime_t)(b) \ || _PyTime_MAX / (_PyTime_t)(b) < (_PyTime_t)(a)) /* To millisecond (10^-3) */ #define SEC_TO_MS 1000 /* To microseconds (10^-6) */ #define MS_TO_US 1000 #define SEC_TO_US (SEC_TO_MS * MS_TO_US) /* To nanoseconds (10^-9) */ #define US_TO_NS 1000 #define MS_TO_NS (MS_TO_US * US_TO_NS) #define SEC_TO_NS (SEC_TO_MS * MS_TO_NS) /* Conversion from nanoseconds */ #define NS_TO_MS (1000 * 1000) #define NS_TO_US (1000) typedef int clockid_t; static void error_time_t_overflow(void) { PyErr_SetString(PyExc_OverflowError, "timestamp out of range for platform time_t"); } _PyTime_t _PyTime_MulDiv(_PyTime_t ticks, _PyTime_t mul, _PyTime_t div) { _PyTime_t intpart, remaining; /* Compute (ticks * mul / div) in two parts to prevent integer overflow: compute integer part, and then the remaining part. (ticks * mul) / div == (ticks / div) * mul + (ticks % div) * mul / div The caller must ensure that "(div - 1) * mul" cannot overflow. */ intpart = ticks / div; ticks %= div; remaining = ticks * mul; remaining /= div; return intpart * mul + remaining; } time_t _PyLong_AsTime_t(PyObject *obj) { #if SIZEOF_TIME_T == SIZEOF_LONG_LONG long long val; val = PyLong_AsLongLong(obj); #else long val; Py_BUILD_ASSERT(sizeof(time_t) <= sizeof(long)); val = PyLong_AsLong(obj); #endif if (val == -1 && PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_OverflowError)) error_time_t_overflow(); return -1; } return (time_t)val; } PyObject * _PyLong_FromTime_t(time_t t) { #if SIZEOF_TIME_T == SIZEOF_LONG_LONG return PyLong_FromLongLong((long long)t); #else Py_BUILD_ASSERT(sizeof(time_t) <= sizeof(long)); return PyLong_FromLong((long)t); #endif } /* Round to nearest with ties going to nearest even integer (_PyTime_ROUND_HALF_EVEN) */ static double _PyTime_RoundHalfEven(double x) { double rounded = round(x); if (fabs(x-rounded) == 0.5) /* halfway case: round to even */ rounded = 2.0*round(x/2.0); return rounded; } static double _PyTime_Round(double x, _PyTime_round_t round) { /* volatile avoids optimization changing how numbers are rounded */ volatile double d; d = x; if (round == _PyTime_ROUND_HALF_EVEN){ d = _PyTime_RoundHalfEven(d); } else if (round == _PyTime_ROUND_CEILING){ d = ceil(d); } else if (round == _PyTime_ROUND_FLOOR) { d = floor(d); } else { assert(round == _PyTime_ROUND_UP); d = (d >= 0.0) ? ceil(d) : floor(d); } return d; } static int _PyTime_DoubleToDenominator(double d, time_t *sec, long *numerator, double denominator, _PyTime_round_t round) { double intpart; /* volatile avoids optimization changing how numbers are rounded */ volatile double floatpart; floatpart = modf(d, &intpart); floatpart *= denominator; floatpart = _PyTime_Round(floatpart, round); if (floatpart >= denominator) { floatpart -= denominator; intpart += 1.0; } else if (floatpart < 0) { floatpart += denominator; intpart -= 1.0; } assert(0.0 <= floatpart && floatpart < denominator); if (!_Py_InIntegralTypeRange(time_t, intpart)) { error_time_t_overflow(); return -1; } *sec = (time_t)intpart; *numerator = (long)floatpart; return 0; } static int _PyTime_ObjectToDenominator(PyObject *obj, time_t *sec, long *numerator, double denominator, _PyTime_round_t round) { assert(denominator <= (double)LONG_MAX); if (PyFloat_Check(obj)) { double d = PyFloat_AsDouble(obj); if (Py_IS_NAN(d)) { *numerator = 0; PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)"); return -1; } return _PyTime_DoubleToDenominator(d, sec, numerator, denominator, round); } else { *sec = _PyLong_AsTime_t(obj); *numerator = 0; if (*sec == (time_t)-1 && PyErr_Occurred()) return -1; return 0; } } int _PyTime_ObjectToTime_t(PyObject *obj, time_t *sec, _PyTime_round_t round) { if (PyFloat_Check(obj)) { double intpart; /* volatile avoids optimization changing how numbers are rounded */ volatile double d; d = PyFloat_AsDouble(obj); if (Py_IS_NAN(d)) { PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)"); return -1; } d = _PyTime_Round(d, round); (void)modf(d, &intpart); if (!_Py_InIntegralTypeRange(time_t, intpart)) { error_time_t_overflow(); return -1; } *sec = (time_t)intpart; return 0; } else { *sec = _PyLong_AsTime_t(obj); if (*sec == (time_t)-1 && PyErr_Occurred()) return -1; return 0; } } int _PyTime_ObjectToTimespec(PyObject *obj, time_t *sec, long *nsec, _PyTime_round_t round) { int res; res = _PyTime_ObjectToDenominator(obj, sec, nsec, 1e9, round); if (res == 0) { assert(0 <= *nsec && *nsec < SEC_TO_NS); } return res; } int _PyTime_ObjectToTimeval(PyObject *obj, time_t *sec, long *usec, _PyTime_round_t round) { int res; res = _PyTime_ObjectToDenominator(obj, sec, usec, 1e6, round); if (res == 0) { assert(0 <= *usec && *usec < SEC_TO_US); } return res; } static void _PyTime_overflow(void) { PyErr_SetString(PyExc_OverflowError, "timestamp too large to convert to C _PyTime_t"); } _PyTime_t _PyTime_FromSeconds(int seconds) { _PyTime_t t; t = (_PyTime_t)seconds; /* ensure that integer overflow cannot happen, int type should have 32 bits, whereas _PyTime_t type has at least 64 bits (SEC_TO_MS takes 30 bits). */ Py_BUILD_ASSERT(INT_MAX <= _PyTime_MAX / SEC_TO_NS); Py_BUILD_ASSERT(INT_MIN >= _PyTime_MIN / SEC_TO_NS); assert((t >= 0 && t <= _PyTime_MAX / SEC_TO_NS) || (t < 0 && t >= _PyTime_MIN / SEC_TO_NS)); t *= SEC_TO_NS; return t; } _PyTime_t _PyTime_FromNanoseconds(long long ns) { _PyTime_t t; Py_BUILD_ASSERT(sizeof(long long) <= sizeof(_PyTime_t)); t = Py_SAFE_DOWNCAST(ns, long long, _PyTime_t); return t; } static int pytime_fromtimespec(_PyTime_t *tp, struct timespec *ts, int raise) { int res = 0; _PyTime_t t; Py_BUILD_ASSERT(sizeof(ts->tv_sec) <= sizeof(_PyTime_t)); t = (_PyTime_t)ts->tv_sec; if (__builtin_mul_overflow(t, SEC_TO_NS, &t)) { if (raise) _PyTime_overflow(); res = -1; } t += ts->tv_nsec; *tp = t; return res; } int _PyTime_FromTimespec(_PyTime_t *tp, struct timespec *ts) { return pytime_fromtimespec(tp, ts, 1); } int pytime_fromtimeval(_PyTime_t *tp, struct timeval *tv, int raise) { _PyTime_t t; int res = 0; Py_BUILD_ASSERT(sizeof(tv->tv_sec) <= sizeof(_PyTime_t)); t = (_PyTime_t)tv->tv_sec; if (__builtin_mul_overflow(t, SEC_TO_NS, &t)) { if (raise) _PyTime_overflow(); res = -1; } t += (_PyTime_t)tv->tv_usec * US_TO_NS; *tp = t; return res; } int _PyTime_FromTimeval(_PyTime_t *tp, struct timeval *tv) { return pytime_fromtimeval(tp, tv, 1); } static int _PyTime_FromFloatObject(_PyTime_t *t, double value, _PyTime_round_t round, long unit_to_ns) { /* volatile avoids optimization changing how numbers are rounded */ volatile double d; /* convert to a number of nanoseconds */ d = value; d *= (double)unit_to_ns; d = _PyTime_Round(d, round); if (!_Py_InIntegralTypeRange(_PyTime_t, d)) { _PyTime_overflow(); return -1; } *t = (_PyTime_t)d; return 0; } static int _PyTime_FromObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round, long unit_to_ns) { if (PyFloat_Check(obj)) { double d; d = PyFloat_AsDouble(obj); if (Py_IS_NAN(d)) { PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)"); return -1; } return _PyTime_FromFloatObject(t, d, round, unit_to_ns); } else { long long sec; Py_BUILD_ASSERT(sizeof(long long) <= sizeof(_PyTime_t)); sec = PyLong_AsLongLong(obj); if (sec == -1 && PyErr_Occurred()) { if (PyErr_ExceptionMatches(PyExc_OverflowError)) _PyTime_overflow(); return -1; } if (_PyTime_check_mul_overflow(sec, unit_to_ns)) { _PyTime_overflow(); return -1; } *t = sec * unit_to_ns; return 0; } } int _PyTime_FromSecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round) { return _PyTime_FromObject(t, obj, round, SEC_TO_NS); } int _PyTime_FromMillisecondsObject(_PyTime_t *t, PyObject *obj, _PyTime_round_t round) { return _PyTime_FromObject(t, obj, round, MS_TO_NS); } double _PyTime_AsSecondsDouble(_PyTime_t t) { /* volatile avoids optimization changing how numbers are rounded */ volatile double d; if (t % SEC_TO_NS == 0) { _PyTime_t secs; /* Divide using integers to avoid rounding issues on the integer part. 1e-9 cannot be stored exactly in IEEE 64-bit. */ secs = t / SEC_TO_NS; d = (double)secs; } else { d = (double)t; d /= 1e9; } return d; } PyObject * _PyTime_AsNanosecondsObject(_PyTime_t t) { Py_BUILD_ASSERT(sizeof(long long) >= sizeof(_PyTime_t)); return PyLong_FromLongLong((long long)t); } static _PyTime_t _PyTime_Divide(const _PyTime_t t, const _PyTime_t k, const _PyTime_round_t round) { assert(k > 1); if (round == _PyTime_ROUND_HALF_EVEN) { _PyTime_t x, r, abs_r; x = t / k; r = t % k; abs_r = Py_ABS(r); if (abs_r > k / 2 || (abs_r == k / 2 && (Py_ABS(x) & 1))) { if (t >= 0) x++; else x--; } return x; } else if (round == _PyTime_ROUND_CEILING) { if (t >= 0){ return (t + k - 1) / k; } else{ return t / k; } } else if (round == _PyTime_ROUND_FLOOR){ if (t >= 0) { return t / k; } else{ return (t - (k - 1)) / k; } } else { assert(round == _PyTime_ROUND_UP); if (t >= 0) { return (t + k - 1) / k; } else { return (t - (k - 1)) / k; } } } _PyTime_t _PyTime_AsMilliseconds(_PyTime_t t, _PyTime_round_t round) { return _PyTime_Divide(t, NS_TO_MS, round); } _PyTime_t _PyTime_AsMicroseconds(_PyTime_t t, _PyTime_round_t round) { return _PyTime_Divide(t, NS_TO_US, round); } static int _PyTime_AsTimeval_impl(_PyTime_t t, _PyTime_t *p_secs, int *p_us, _PyTime_round_t round) { _PyTime_t secs, ns; int usec; int res = 0; secs = t / SEC_TO_NS; ns = t % SEC_TO_NS; usec = (int)_PyTime_Divide(ns, US_TO_NS, round); if (usec < 0) { usec += SEC_TO_US; if (secs != _PyTime_MIN) secs -= 1; else res = -1; } else if (usec >= SEC_TO_US) { usec -= SEC_TO_US; if (secs != _PyTime_MAX) secs += 1; else res = -1; } assert(0 <= usec && usec < SEC_TO_US); *p_secs = secs; *p_us = usec; return res; } static int _PyTime_AsTimevalStruct_impl(_PyTime_t t, struct timeval *tv, _PyTime_round_t round, int raise) { _PyTime_t secs, secs2; int us; int res; res = _PyTime_AsTimeval_impl(t, &secs, &us, round); #ifdef MS_WINDOWS tv->tv_sec = (long)secs; #else tv->tv_sec = secs; #endif tv->tv_usec = us; secs2 = (_PyTime_t)tv->tv_sec; if (res < 0 || secs2 != secs) { if (raise) error_time_t_overflow(); return -1; } return 0; } int _PyTime_AsTimeval(_PyTime_t t, struct timeval *tv, _PyTime_round_t round) { return _PyTime_AsTimevalStruct_impl(t, tv, round, 1); } int _PyTime_AsTimeval_noraise(_PyTime_t t, struct timeval *tv, _PyTime_round_t round) { return _PyTime_AsTimevalStruct_impl(t, tv, round, 0); } int _PyTime_AsTimevalTime_t(_PyTime_t t, time_t *p_secs, int *us, _PyTime_round_t round) { _PyTime_t secs; int res; res = _PyTime_AsTimeval_impl(t, &secs, us, round); *p_secs = secs; if (res < 0 || (_PyTime_t)*p_secs != secs) { error_time_t_overflow(); return -1; } return 0; } static int win_perf_counter_frequency(int64_t *pfrequency, int raise) { int64_t frequency; if (!QueryPerformanceFrequency(&frequency)) { if (raise) { PyErr_SetFromWindowsErr(0); } return -1; } /* Sanity check: should never occur in practice */ if (frequency < 1) { if (raise) { PyErr_SetString(PyExc_RuntimeError, "invalid QueryPerformanceFrequency"); } return -1; } /* Check that frequency can be casted to _PyTime_t. * * Make also sure that (ticks * SEC_TO_NS) cannot overflow in * _PyTime_MulDiv(), with ticks < frequency. * * Known QueryPerformanceFrequency() values: * * - 10,000,000 (10 MHz): 100 ns resolution * - 3,579,545 Hz (3.6 MHz): 279 ns resolution * * None of these frequencies can overflow with 64-bit _PyTime_t, but * check for overflow, just in case. */ if (frequency > _PyTime_MAX || frequency > (int64_t)_PyTime_MAX / (int64_t)SEC_TO_NS) { if (raise) { PyErr_SetString(PyExc_OverflowError, "QueryPerformanceFrequency is too large"); } return -1; } *pfrequency = frequency; return 0; } static int py_get_win_perf_counter(_PyTime_t *tp, _Py_clock_info_t *info, int raise) { static int64_t frequency; if (!frequency) { if (win_perf_counter_frequency(&frequency, raise) < 0) { return -1; } } if (info) { info->implementation = "QueryPerformanceCounter()"; info->resolution = 1 / (double)frequency; info->monotonic = 1; info->adjustable = 0; } int64_t ticksll; QueryPerformanceCounter(&ticksll); /* Make sure that casting int64_t to _PyTime_t cannot overflow, both types are signed */ _PyTime_t ticks; Py_BUILD_ASSERT(sizeof(ticksll) <= sizeof(ticks)); ticks = (_PyTime_t)ticksll; *tp = _PyTime_MulDiv(ticks, SEC_TO_NS, (_PyTime_t)frequency); return 0; } int _PyTime_GetPerfCounterWithInfo(_PyTime_t *t, _Py_clock_info_t *info) { if (!IsWindows()) { return _PyTime_GetMonotonicClockWithInfo(t, info); } else { return py_get_win_perf_counter(t, info, 1); } } int _PyTime_AsTimespec(_PyTime_t t, struct timespec *ts) { _PyTime_t secs, nsec; secs = t / SEC_TO_NS; nsec = t % SEC_TO_NS; if (nsec < 0) { nsec += SEC_TO_NS; secs -= 1; } ts->tv_sec = (time_t)secs; assert(0 <= nsec && nsec < SEC_TO_NS); ts->tv_nsec = nsec; if ((_PyTime_t)ts->tv_sec != secs) { error_time_t_overflow(); return -1; } return 0; } static int pygettimeofday(_PyTime_t *tp, _Py_clock_info_t *info, int raise) { if (IsWindows()) { uint64_t large; struct NtFileTime system_time; assert(info == NULL || raise); GetSystemTimeAsFileTime(&system_time); large = system_time.dwHighDateTime; large <<= 32; large |= system_time.dwLowDateTime; /* 11,644,473,600,000,000,000: number of nanoseconds between the 1st january 1601 and the 1st january 1970 (369 years + 89 leap days). */ *tp = large * 100 - 11644473600000000000ull; if (info) { bool32 isTimeAdjustmentDisabled; uint32_t timeAdjustment, timeIncrement; info->implementation = "GetSystemTimeAsFileTime()"; info->monotonic = 0; if (!GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement, &isTimeAdjustmentDisabled)) { PyErr_SetFromWindowsErr(0); return -1; } info->resolution = timeIncrement * 1e-7; info->adjustable = 1; } } else { int err; struct timespec ts; assert(info == NULL || raise); err = clock_gettime(CLOCK_REALTIME, &ts); if (err) { if (raise) PyErr_SetFromErrno(PyExc_OSError); return -1; } if (pytime_fromtimespec(tp, &ts, raise) < 0) return -1; if (info) { struct timespec res; info->implementation = "clock_gettime(CLOCK_REALTIME)"; info->monotonic = 0; info->adjustable = 1; if (clock_getres(CLOCK_REALTIME, &res) == 0) info->resolution = res.tv_sec + res.tv_nsec * 1e-9; else info->resolution = 1e-9; } } return 0; } _PyTime_t _PyTime_GetSystemClock(void) { _PyTime_t t; if (pygettimeofday(&t, NULL, 0) < 0) { /* should not happen, _PyTime_Init() checked the clock at startup */ assert(0); /* use a fixed value instead of a random value from the stack */ t = 0; } return t; } int _PyTime_GetSystemClockWithInfo(_PyTime_t *t, _Py_clock_info_t *info) { return pygettimeofday(t, info, 1); } static int pymonotonic(_PyTime_t *tp, _Py_clock_info_t *info, int raise) { if (IsWindows()) { uint64_t ticks; _PyTime_t t; assert(info == NULL || raise); ticks = GetTickCount64(); Py_BUILD_ASSERT(sizeof(ticks) <= sizeof(_PyTime_t)); t = (_PyTime_t)ticks; if (__builtin_mul_overflow(t, MS_TO_NS, &t)) { if (raise) { _PyTime_overflow(); return -1; } /* Hello, time traveler! */ assert(0); } *tp = t * MS_TO_NS; if (info) { uint32_t timeAdjustment, timeIncrement; bool32 isTimeAdjustmentDisabled, ok; info->implementation = "GetTickCount64()"; info->monotonic = 1; ok = GetSystemTimeAdjustment(&timeAdjustment, &timeIncrement, &isTimeAdjustmentDisabled); if (!ok) { PyErr_SetFromWindowsErr(0); return -1; } info->resolution = timeIncrement * 1e-7; info->adjustable = 0; } return 0; } #ifdef __APPLE__ static mach_timebase_info_data_t timebase; uint64_t time; if (timebase.denom == 0) { /* According to the Technical Q&A QA1398, mach_timebase_info() cannot fail: https://developer.apple.com/library/mac/#qa/qa1398/ */ (void)mach_timebase_info(&timebase); } time = mach_absolute_time(); /* apply timebase factor */ time *= timebase.numer; time /= timebase.denom; *tp = time; if (info) { info->implementation = "mach_absolute_time()"; info->resolution = (double)timebase.numer / timebase.denom * 1e-9; info->monotonic = 1; info->adjustable = 0; } #else struct timespec ts; #ifdef CLOCK_HIGHRES const clockid_t clk_id = CLOCK_HIGHRES; const char *implementation = "clock_gettime(CLOCK_HIGHRES)"; #else const clockid_t clk_id = CLOCK_MONOTONIC; const char *implementation = "clock_gettime(CLOCK_MONOTONIC)"; #endif assert(info == NULL || raise); if (clock_gettime(clk_id, &ts) != 0) { if (raise) { PyErr_SetFromErrno(PyExc_OSError); return -1; } return -1; } if (info) { struct timespec res; info->monotonic = 1; info->implementation = implementation; info->adjustable = 0; if (clock_getres(clk_id, &res) != 0) { PyErr_SetFromErrno(PyExc_OSError); return -1; } info->resolution = res.tv_sec + res.tv_nsec * 1e-9; } if (pytime_fromtimespec(tp, &ts, raise) < 0) return -1; #endif return 0; } _PyTime_t _PyTime_GetMonotonicClock(void) { _PyTime_t t; if (pymonotonic(&t, NULL, 0) < 0) { /* should not happen, _PyTime_Init() checked that monotonic clock at startup */ assert(0); /* use a fixed value instead of a random value from the stack */ t = 0; } return t; } int _PyTime_GetMonotonicClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info) { return pymonotonic(tp, info, 1); } int _PyTime_Init(void) { _PyTime_t t; /* ensure that the system clock works */ if (_PyTime_GetSystemClockWithInfo(&t, NULL) < 0) return -1; /* ensure that the operating system provides a monotonic clock */ if (_PyTime_GetMonotonicClockWithInfo(&t, NULL) < 0) return -1; return 0; } int _PyTime_localtime(time_t t, struct tm *tm) { #ifdef MS_WINDOWS int error; error = localtime_s(tm, &t); if (error != 0) { errno = error; PyErr_SetFromErrno(PyExc_OSError); return -1; } return 0; #else /* !MS_WINDOWS */ if (localtime_r(&t, tm) == NULL) { #ifdef EINVAL if (errno == 0) errno = EINVAL; #endif PyErr_SetFromErrno(PyExc_OSError); return -1; } return 0; #endif /* MS_WINDOWS */ } int _PyTime_gmtime(time_t t, struct tm *tm) { #ifdef MS_WINDOWS int error; error = gmtime_s(tm, &t); if (error != 0) { errno = error; PyErr_SetFromErrno(PyExc_OSError); return -1; } return 0; #else /* !MS_WINDOWS */ if (gmtime_r(&t, tm) == NULL) { #ifdef EINVAL if (errno == 0) errno = EINVAL; #endif PyErr_SetFromErrno(PyExc_OSError); return -1; } return 0; #endif /* MS_WINDOWS */ }
23,846
886
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/fdisinteractive.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/calls.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pylifecycle.h" /* clang-format off */ /* * The file descriptor fd is considered ``interactive'' if either * a) isatty(fd) is TRUE, or * b) the -i flag was given, and the filename associated with * the descriptor is NULL or "<stdin>" or "???". */ int Py_FdIsInteractive(FILE *fp, const char *filename) { if (isatty((int)fileno(fp))) return 1; if (!Py_InteractiveFlag) return 0; return (filename == NULL) || (strcmp(filename, "<stdin>") == 0) || (strcmp(filename, "???") == 0); }
1,474
29
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/getcopyright.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/cmpxchg.h" #include "libc/intrin/weaken.h" #include "libc/stdio/append.h" #include "libc/str/str.h" #include "third_party/python/Include/pylifecycle.h" /* clang-format off */ asm(".ident\t\"\\n\\n\ Python 3.6 (https://docs.python.org/3/license.html)\\n\ Copyright (c) 2001-2021 Python Software Foundation.\\n\ All Rights Reserved.\\n\ Copyright (c) 2000 BeOpen.com.\\n\ All Rights Reserved.\\n\ Copyright (c) 1995-2001 Corporation for National Research Initiatives.\\n\ All Rights Reserved.\\n\ Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\\n\ All Rights Reserved.\""); extern const char kLegalNotices[]; const char * Py_GetCopyright(void) { const char *p; static bool once; static char *res; if (_cmpxchg(&once, 0, 1)) { appends(&res, ""); for (p = *_weaken(kLegalNotices); *p; p += strlen(p) + 1) { appends(&res, p); } } return res; }
1,760
41
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pythonhome.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/str/str.h" #include "third_party/python/Include/osdefs.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymacro.h" /* clang-format off */ static wchar_t *default_home = NULL; static wchar_t env_home[MAXPATHLEN+1]; void Py_SetPythonHome(wchar_t *home) { default_home = home; } wchar_t * Py_GetPythonHome(void) { wchar_t *home = default_home; if (home == NULL && !Py_IgnoreEnvironmentFlag) { char* chome = Py_GETENV("PYTHONHOME"); if (chome) { size_t size = Py_ARRAY_LENGTH(env_home); size_t r = mbstowcs(env_home, chome, size); if (r != (size_t)-1 && r < size) home = env_home; } } return home; }
1,617
38
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/codecs.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/intrin/weaken.h" #include "libc/stdio/stdio.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/bytesobject.h" #include "third_party/python/Include/ceval.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/pycapsule.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/ucnhash.h" #include "third_party/python/Modules/unicodedata.h" /* clang-format off */ /* ------------------------------------------------------------------------ Python Codec Registry and support functions Written by Marc-Andre Lemburg ([email protected]). Copyright (c) Corporation for National Research Initiatives. ------------------------------------------------------------------------ */ const char *Py_hexdigits = "0123456789abcdef"; /* --- Codec Registry ----------------------------------------------------- */ /* Import the standard encodings package which will register the first codec search function. This is done in a lazy way so that the Unicode implementation does not downgrade startup time of scripts not needing it. ImportErrors are silently ignored by this function. Only one try is made. */ static int _PyCodecRegistry_Init(void); /* Forward */ int PyCodec_Register(PyObject *search_function) { PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) goto onError; if (search_function == NULL) { PyErr_BadArgument(); goto onError; } if (!PyCallable_Check(search_function)) { PyErr_SetString(PyExc_TypeError, "argument must be callable"); goto onError; } return PyList_Append(interp->codec_search_path, search_function); onError: return -1; } /* Convert a string to a normalized Python string: all characters are converted to lower case, spaces are replaced with underscores. */ static PyObject *normalizestring(const char *string) { size_t i; size_t len = strlen(string); char *p; PyObject *v; if (len > PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "string is too large"); return NULL; } p = PyMem_Malloc(len + 1); if (p == NULL) return PyErr_NoMemory(); for (i = 0; i < len; i++) { char ch = string[i]; if (ch == ' ') ch = '-'; else ch = Py_TOLOWER(ch); p[i] = ch; } p[i] = '\0'; v = PyUnicode_FromString(p); PyMem_Free(p); return v; } /* Lookup the given encoding and return a tuple providing the codec facilities. 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 LookupError 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. */ PyObject *_PyCodec_Lookup(const char *encoding) { PyInterpreterState *interp; PyObject *result, *args = NULL, *v; Py_ssize_t i, len; if (encoding == NULL) { PyErr_BadArgument(); goto onError; } interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) goto onError; /* Convert the encoding to a normalized Python string: all characters are converted to lower case, spaces and hyphens are replaced with underscores. */ v = normalizestring(encoding); if (v == NULL) goto onError; PyUnicode_InternInPlace(&v); /* First, try to lookup the name in the registry dictionary */ result = PyDict_GetItem(interp->codec_search_cache, v); if (result != NULL) { Py_INCREF(result); Py_DECREF(v); return result; } /* Next, scan the search functions in order of registration */ args = PyTuple_New(1); if (args == NULL) { Py_DECREF(v); return NULL; } PyTuple_SET_ITEM(args,0,v); len = PyList_Size(interp->codec_search_path); if (len < 0) goto onError; if (len == 0) { PyErr_SetString(PyExc_LookupError, "no codec search functions registered: " "can't find encoding"); goto onError; } for (i = 0; i < len; i++) { PyObject *func; func = PyList_GetItem(interp->codec_search_path, i); if (func == NULL) goto onError; result = PyEval_CallObject(func, args); if (result == NULL) goto onError; if (result == Py_None) { Py_DECREF(result); continue; } if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) { PyErr_SetString(PyExc_TypeError, "codec search functions must return 4-tuples"); Py_DECREF(result); goto onError; } break; } if (i == len) { /* XXX Perhaps we should cache misses too ? */ PyErr_Format(PyExc_LookupError, "unknown encoding: %s", encoding); goto onError; } /* Cache and return the result */ if (PyDict_SetItem(interp->codec_search_cache, v, result) < 0) { Py_DECREF(result); goto onError; } Py_DECREF(args); return result; onError: Py_XDECREF(args); return NULL; } int _PyCodec_Forget(const char *encoding) { PyInterpreterState *interp; PyObject *v; int result; interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL) { return -1; } /* Convert the encoding to a normalized Python string: all characters are converted to lower case, spaces and hyphens are replaced with underscores. */ v = normalizestring(encoding); if (v == NULL) { return -1; } /* Drop the named codec from the internal cache */ result = PyDict_DelItem(interp->codec_search_cache, v); Py_DECREF(v); return result; } /* Codec registry encoding check API. */ int PyCodec_KnownEncoding(const char *encoding) { PyObject *codecs; codecs = _PyCodec_Lookup(encoding); if (!codecs) { PyErr_Clear(); return 0; } else { Py_DECREF(codecs); return 1; } } static PyObject *args_tuple(PyObject *object, const char *errors) { PyObject *args; args = PyTuple_New(1 + (errors != NULL)); if (args == NULL) return NULL; Py_INCREF(object); PyTuple_SET_ITEM(args,0,object); if (errors) { PyObject *v; v = PyUnicode_FromString(errors); if (v == NULL) { Py_DECREF(args); return NULL; } PyTuple_SET_ITEM(args, 1, v); } return args; } /* Helper function to get a codec item */ static PyObject *codec_getitem(const char *encoding, int index) { PyObject *codecs; PyObject *v; codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) return NULL; v = PyTuple_GET_ITEM(codecs, index); Py_DECREF(codecs); Py_INCREF(v); return v; } /* Helper functions to create an incremental codec. */ static PyObject *codec_makeincrementalcodec(PyObject *codec_info, const char *errors, const char *attrname) { PyObject *ret, *inccodec; inccodec = PyObject_GetAttrString(codec_info, attrname); if (inccodec == NULL) return NULL; if (errors) ret = PyObject_CallFunction(inccodec, "s", errors); else ret = PyObject_CallFunction(inccodec, NULL); Py_DECREF(inccodec); return ret; } static PyObject *codec_getincrementalcodec(const char *encoding, const char *errors, const char *attrname) { PyObject *codec_info, *ret; codec_info = _PyCodec_Lookup(encoding); if (codec_info == NULL) return NULL; ret = codec_makeincrementalcodec(codec_info, errors, attrname); Py_DECREF(codec_info); return ret; } /* Helper function to create a stream codec. */ static PyObject *codec_getstreamcodec(const char *encoding, PyObject *stream, const char *errors, const int index) { PyObject *codecs, *streamcodec, *codeccls; codecs = _PyCodec_Lookup(encoding); if (codecs == NULL) return NULL; codeccls = PyTuple_GET_ITEM(codecs, index); if (errors != NULL) streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors); else streamcodec = PyObject_CallFunction(codeccls, "O", stream); Py_DECREF(codecs); return streamcodec; } /* Helpers to work with the result of _PyCodec_Lookup */ PyObject *_PyCodecInfo_GetIncrementalDecoder(PyObject *codec_info, const char *errors) { return codec_makeincrementalcodec(codec_info, errors, "incrementaldecoder"); } PyObject *_PyCodecInfo_GetIncrementalEncoder(PyObject *codec_info, const char *errors) { return codec_makeincrementalcodec(codec_info, errors, "incrementalencoder"); } /* Convenience APIs to query the Codec registry. All APIs return a codec object with incremented refcount. */ PyObject *PyCodec_Encoder(const char *encoding) { return codec_getitem(encoding, 0); } PyObject *PyCodec_Decoder(const char *encoding) { return codec_getitem(encoding, 1); } PyObject *PyCodec_IncrementalEncoder(const char *encoding, const char *errors) { return codec_getincrementalcodec(encoding, errors, "incrementalencoder"); } PyObject *PyCodec_IncrementalDecoder(const char *encoding, const char *errors) { return codec_getincrementalcodec(encoding, errors, "incrementaldecoder"); } PyObject *PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors) { return codec_getstreamcodec(encoding, stream, errors, 2); } PyObject *PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors) { return codec_getstreamcodec(encoding, stream, errors, 3); } /* Helper that tries to ensure the reported exception chain indicates the * codec that was invoked to trigger the failure without changing the type * of the exception raised. */ static void wrap_codec_error(const char *operation, const char *encoding) { /* TrySetFromCause will replace the active exception with a suitably * updated clone if it can, otherwise it will leave the original * exception alone. */ _PyErr_TrySetFromCause("%s with '%s' codec failed", operation, encoding); } /* Encode an object (e.g. a Unicode object) using the given encoding and return the resulting encoded object (usually a Python string). errors is passed to the encoder factory as argument if non-NULL. */ static PyObject * _PyCodec_EncodeInternal(PyObject *object, PyObject *encoder, const char *encoding, const char *errors) { PyObject *args = NULL, *result = NULL; PyObject *v = NULL; args = args_tuple(object, errors); if (args == NULL) goto onError; result = PyEval_CallObject(encoder, args); if (result == NULL) { wrap_codec_error("encoding", encoding); goto onError; } if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 2) { PyErr_SetString(PyExc_TypeError, "encoder must return a tuple (object, integer)"); goto onError; } v = PyTuple_GET_ITEM(result,0); Py_INCREF(v); /* We don't check or use the second (integer) entry. */ Py_DECREF(args); Py_DECREF(encoder); Py_DECREF(result); return v; onError: Py_XDECREF(result); Py_XDECREF(args); Py_XDECREF(encoder); return NULL; } /* Decode an object (usually a Python string) using the given encoding and return an equivalent object (e.g. a Unicode object). errors is passed to the decoder factory as argument if non-NULL. */ static PyObject * _PyCodec_DecodeInternal(PyObject *object, PyObject *decoder, const char *encoding, const char *errors) { PyObject *args = NULL, *result = NULL; PyObject *v; args = args_tuple(object, errors); if (args == NULL) goto onError; result = PyEval_CallObject(decoder,args); if (result == NULL) { wrap_codec_error("decoding", encoding); goto onError; } if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 2) { PyErr_SetString(PyExc_TypeError, "decoder must return a tuple (object,integer)"); goto onError; } v = PyTuple_GET_ITEM(result,0); Py_INCREF(v); /* We don't check or use the second (integer) entry. */ Py_DECREF(args); Py_DECREF(decoder); Py_DECREF(result); return v; onError: Py_XDECREF(args); Py_XDECREF(decoder); Py_XDECREF(result); return NULL; } /* Generic encoding/decoding API */ PyObject *PyCodec_Encode(PyObject *object, const char *encoding, const char *errors) { PyObject *encoder; encoder = PyCodec_Encoder(encoding); if (encoder == NULL) return NULL; return _PyCodec_EncodeInternal(object, encoder, encoding, errors); } PyObject *PyCodec_Decode(PyObject *object, const char *encoding, const char *errors) { PyObject *decoder; decoder = PyCodec_Decoder(encoding); if (decoder == NULL) return NULL; return _PyCodec_DecodeInternal(object, decoder, encoding, errors); } /* Text encoding/decoding API */ PyObject * _PyCodec_LookupTextEncoding(const char *encoding, const char *alternate_command) { _Py_IDENTIFIER(_is_text_encoding); PyObject *codec; PyObject *attr; int is_text_codec; codec = _PyCodec_Lookup(encoding); if (codec == NULL) return NULL; /* Backwards compatibility: assume any raw tuple describes a text * encoding, and the same for anything lacking the private * attribute. */ if (!PyTuple_CheckExact(codec)) { attr = _PyObject_GetAttrId(codec, &PyId__is_text_encoding); if (attr == NULL) { if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } else { Py_DECREF(codec); return NULL; } } else { is_text_codec = PyObject_IsTrue(attr); Py_DECREF(attr); if (is_text_codec <= 0) { Py_DECREF(codec); if (!is_text_codec) PyErr_Format(PyExc_LookupError, "'%.400s' is not a text encoding; " "use %s to handle arbitrary codecs", encoding, alternate_command); return NULL; } } } /* This appears to be a valid text encoding */ return codec; } static PyObject *codec_getitem_checked(const char *encoding, const char *alternate_command, int index) { PyObject *codec; PyObject *v; codec = _PyCodec_LookupTextEncoding(encoding, alternate_command); if (codec == NULL) return NULL; v = PyTuple_GET_ITEM(codec, index); Py_INCREF(v); Py_DECREF(codec); return v; } static PyObject * _PyCodec_TextEncoder(const char *encoding) { return codec_getitem_checked(encoding, "codecs.encode()", 0); } static PyObject * _PyCodec_TextDecoder(const char *encoding) { return codec_getitem_checked(encoding, "codecs.decode()", 1); } PyObject *_PyCodec_EncodeText(PyObject *object, const char *encoding, const char *errors) { PyObject *encoder; encoder = _PyCodec_TextEncoder(encoding); if (encoder == NULL) return NULL; return _PyCodec_EncodeInternal(object, encoder, encoding, errors); } PyObject *_PyCodec_DecodeText(PyObject *object, const char *encoding, const char *errors) { PyObject *decoder; decoder = _PyCodec_TextDecoder(encoding); if (decoder == NULL) return NULL; return _PyCodec_DecodeInternal(object, decoder, encoding, errors); } /* Register the error handling callback function error under the name name. This function will be called by the codec when it encounters an 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) { PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) return -1; if (!PyCallable_Check(error)) { PyErr_SetString(PyExc_TypeError, "handler must be callable"); return -1; } return PyDict_SetItemString(interp->codec_error_registry, name, error); } /* Lookup the error handling callback function registered under the name error. As a special case NULL can be passed, in which case the error handling callback for strict encoding will be returned. */ PyObject *PyCodec_LookupError(const char *name) { PyObject *handler = NULL; PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) return NULL; if (name==NULL) name = "strict"; handler = PyDict_GetItemString(interp->codec_error_registry, name); if (!handler) PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name); else Py_INCREF(handler); return handler; } static void wrong_exception_type(PyObject *exc) { PyErr_Format(PyExc_TypeError, "don't know how to handle %.200s in error callback", exc->ob_type->tp_name); } PyObject *PyCodec_StrictErrors(PyObject *exc) { if (PyExceptionInstance_Check(exc)) PyErr_SetObject(PyExceptionInstance_Class(exc), exc); else PyErr_SetString(PyExc_TypeError, "codec must pass exception instance"); return NULL; } PyObject *PyCodec_IgnoreErrors(PyObject *exc) { Py_ssize_t end; if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) { if (PyUnicodeEncodeError_GetEnd(exc, &end)) return NULL; } else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeDecodeError)) { if (PyUnicodeDecodeError_GetEnd(exc, &end)) return NULL; } else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeTranslateError)) { if (PyUnicodeTranslateError_GetEnd(exc, &end)) return NULL; } else { wrong_exception_type(exc); return NULL; } return Py_BuildValue("(Nn)", PyUnicode_New(0, 0), end); } PyObject *PyCodec_ReplaceErrors(PyObject *exc) { Py_ssize_t start, end, i, len; if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) { PyObject *res; int kind; void *data; if (PyUnicodeEncodeError_GetStart(exc, &start)) return NULL; if (PyUnicodeEncodeError_GetEnd(exc, &end)) return NULL; len = end - start; res = PyUnicode_New(len, '?'); if (res == NULL) return NULL; kind = PyUnicode_KIND(res); data = PyUnicode_DATA(res); for (i = 0; i < len; ++i) PyUnicode_WRITE(kind, data, i, '?'); assert(_PyUnicode_CheckConsistency(res, 1)); return Py_BuildValue("(Nn)", res, end); } else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeDecodeError)) { if (PyUnicodeDecodeError_GetEnd(exc, &end)) return NULL; return Py_BuildValue("(Cn)", (int)Py_UNICODE_REPLACEMENT_CHARACTER, end); } else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeTranslateError)) { PyObject *res; int kind; void *data; if (PyUnicodeTranslateError_GetStart(exc, &start)) return NULL; if (PyUnicodeTranslateError_GetEnd(exc, &end)) return NULL; len = end - start; res = PyUnicode_New(len, Py_UNICODE_REPLACEMENT_CHARACTER); if (res == NULL) return NULL; kind = PyUnicode_KIND(res); data = PyUnicode_DATA(res); for (i=0; i < len; i++) PyUnicode_WRITE(kind, data, i, Py_UNICODE_REPLACEMENT_CHARACTER); assert(_PyUnicode_CheckConsistency(res, 1)); return Py_BuildValue("(Nn)", res, end); } else { wrong_exception_type(exc); return NULL; } } PyObject *PyCodec_XMLCharRefReplaceErrors(PyObject *exc) { if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) { PyObject *restuple; PyObject *object; Py_ssize_t i; Py_ssize_t start; Py_ssize_t end; PyObject *res; unsigned char *outp; Py_ssize_t ressize; Py_UCS4 ch; if (PyUnicodeEncodeError_GetStart(exc, &start)) return NULL; if (PyUnicodeEncodeError_GetEnd(exc, &end)) return NULL; if (!(object = PyUnicodeEncodeError_GetObject(exc))) return NULL; if (end - start > PY_SSIZE_T_MAX / (2+7+1)) end = start + PY_SSIZE_T_MAX / (2+7+1); for (i = start, ressize = 0; i < end; ++i) { /* object is guaranteed to be "ready" */ ch = PyUnicode_READ_CHAR(object, i); if (ch<10) ressize += 2+1+1; else if (ch<100) ressize += 2+2+1; else if (ch<1000) ressize += 2+3+1; else if (ch<10000) ressize += 2+4+1; else if (ch<100000) ressize += 2+5+1; else if (ch<1000000) ressize += 2+6+1; else ressize += 2+7+1; } /* allocate replacement */ res = PyUnicode_New(ressize, 127); if (res == NULL) { Py_DECREF(object); return NULL; } outp = PyUnicode_1BYTE_DATA(res); /* generate replacement */ for (i = start; i < end; ++i) { int digits; int base; ch = PyUnicode_READ_CHAR(object, i); *outp++ = '&'; *outp++ = '#'; if (ch<10) { digits = 1; base = 1; } else if (ch<100) { digits = 2; base = 10; } else if (ch<1000) { digits = 3; base = 100; } else if (ch<10000) { digits = 4; base = 1000; } else if (ch<100000) { digits = 5; base = 10000; } else if (ch<1000000) { digits = 6; base = 100000; } else { digits = 7; base = 1000000; } while (digits-->0) { *outp++ = '0' + ch/base; ch %= base; base /= 10; } *outp++ = ';'; } assert(_PyUnicode_CheckConsistency(res, 1)); restuple = Py_BuildValue("(Nn)", res, end); Py_DECREF(object); return restuple; } else { wrong_exception_type(exc); return NULL; } } PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc) { PyObject *object; Py_ssize_t i; Py_ssize_t start; Py_ssize_t end; PyObject *res; unsigned char *outp; int ressize; Py_UCS4 c; if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeDecodeError)) { unsigned char *p; if (PyUnicodeDecodeError_GetStart(exc, &start)) return NULL; if (PyUnicodeDecodeError_GetEnd(exc, &end)) return NULL; if (!(object = PyUnicodeDecodeError_GetObject(exc))) return NULL; if (!(p = (unsigned char*)PyBytes_AsString(object))) { Py_DECREF(object); return NULL; } res = PyUnicode_New(4 * (end - start), 127); if (res == NULL) { Py_DECREF(object); return NULL; } outp = PyUnicode_1BYTE_DATA(res); for (i = start; i < end; i++, outp += 4) { unsigned char c = p[i]; outp[0] = '\\'; outp[1] = 'x'; outp[2] = Py_hexdigits[(c>>4)&0xf]; outp[3] = Py_hexdigits[c&0xf]; } assert(_PyUnicode_CheckConsistency(res, 1)); Py_DECREF(object); return Py_BuildValue("(Nn)", res, end); } if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) { if (PyUnicodeEncodeError_GetStart(exc, &start)) return NULL; if (PyUnicodeEncodeError_GetEnd(exc, &end)) return NULL; if (!(object = PyUnicodeEncodeError_GetObject(exc))) return NULL; } else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeTranslateError)) { if (PyUnicodeTranslateError_GetStart(exc, &start)) return NULL; if (PyUnicodeTranslateError_GetEnd(exc, &end)) return NULL; if (!(object = PyUnicodeTranslateError_GetObject(exc))) return NULL; } else { wrong_exception_type(exc); return NULL; } if (end - start > PY_SSIZE_T_MAX / (1+1+8)) end = start + PY_SSIZE_T_MAX / (1+1+8); for (i = start, ressize = 0; i < end; ++i) { /* object is guaranteed to be "ready" */ c = PyUnicode_READ_CHAR(object, i); if (c >= 0x10000) { ressize += 1+1+8; } else if (c >= 0x100) { ressize += 1+1+4; } else ressize += 1+1+2; } res = PyUnicode_New(ressize, 127); if (res == NULL) { Py_DECREF(object); return NULL; } outp = PyUnicode_1BYTE_DATA(res); for (i = start; i < end; ++i) { c = PyUnicode_READ_CHAR(object, i); *outp++ = '\\'; if (c >= 0x00010000) { *outp++ = 'U'; *outp++ = Py_hexdigits[(c>>28)&0xf]; *outp++ = Py_hexdigits[(c>>24)&0xf]; *outp++ = Py_hexdigits[(c>>20)&0xf]; *outp++ = Py_hexdigits[(c>>16)&0xf]; *outp++ = Py_hexdigits[(c>>12)&0xf]; *outp++ = Py_hexdigits[(c>>8)&0xf]; } else if (c >= 0x100) { *outp++ = 'u'; *outp++ = Py_hexdigits[(c>>12)&0xf]; *outp++ = Py_hexdigits[(c>>8)&0xf]; } else *outp++ = 'x'; *outp++ = Py_hexdigits[(c>>4)&0xf]; *outp++ = Py_hexdigits[c&0xf]; } assert(_PyUnicode_CheckConsistency(res, 1)); Py_DECREF(object); return Py_BuildValue("(Nn)", res, end); } PyObject *PyCodec_NameReplaceErrors(PyObject *exc) { if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) { PyObject *restuple; PyObject *object; Py_ssize_t i; Py_ssize_t start; Py_ssize_t end; PyObject *res; unsigned char *outp; Py_ssize_t ressize; int replsize; Py_UCS4 c; char buffer[256]; /* NAME_MAXLEN */ if (PyUnicodeEncodeError_GetStart(exc, &start)) return NULL; if (PyUnicodeEncodeError_GetEnd(exc, &end)) return NULL; if (!(object = PyUnicodeEncodeError_GetObject(exc))) return NULL; for (i = start, ressize = 0; i < end; ++i) { /* object is guaranteed to be "ready" */ if (!_weaken(_PyUnicode_GetUcName)) { PyErr_SetString( PyExc_UnicodeError, "_PyUnicode_GetUcName() not available"); return NULL; } c = PyUnicode_READ_CHAR(object, i); if (_weaken(_PyUnicode_GetUcName)(NULL, c, buffer, sizeof(buffer), 1)) { replsize = 1+1+1+(int)strlen(buffer)+1; } else if (c >= 0x10000) { replsize = 1+1+8; } else if (c >= 0x100) { replsize = 1+1+4; } else replsize = 1+1+2; if (ressize > PY_SSIZE_T_MAX - replsize) break; ressize += replsize; } end = i; res = PyUnicode_New(ressize, 127); if (res==NULL) return NULL; for (i = start, outp = PyUnicode_1BYTE_DATA(res); i < end; ++i) { c = PyUnicode_READ_CHAR(object, i); *outp++ = '\\'; if (_PyUnicode_GetUcName(NULL, c, buffer, sizeof(buffer), 1)) { *outp++ = 'N'; *outp++ = '{'; strcpy((char *)outp, buffer); outp += strlen(buffer); *outp++ = '}'; continue; } if (c >= 0x00010000) { *outp++ = 'U'; *outp++ = Py_hexdigits[(c>>28)&0xf]; *outp++ = Py_hexdigits[(c>>24)&0xf]; *outp++ = Py_hexdigits[(c>>20)&0xf]; *outp++ = Py_hexdigits[(c>>16)&0xf]; *outp++ = Py_hexdigits[(c>>12)&0xf]; *outp++ = Py_hexdigits[(c>>8)&0xf]; } else if (c >= 0x100) { *outp++ = 'u'; *outp++ = Py_hexdigits[(c>>12)&0xf]; *outp++ = Py_hexdigits[(c>>8)&0xf]; } else *outp++ = 'x'; *outp++ = Py_hexdigits[(c>>4)&0xf]; *outp++ = Py_hexdigits[c&0xf]; } assert(outp == PyUnicode_1BYTE_DATA(res) + ressize); assert(_PyUnicode_CheckConsistency(res, 1)); restuple = Py_BuildValue("(Nn)", res, end); Py_DECREF(object); return restuple; } else { wrong_exception_type(exc); return NULL; } } #define ENC_UNKNOWN -1 #define ENC_UTF8 0 #define ENC_UTF16BE 1 #define ENC_UTF16LE 2 #define ENC_UTF32BE 3 #define ENC_UTF32LE 4 static int get_standard_encoding(const char *encoding, int *bytelength) { if (Py_TOLOWER(encoding[0]) == 'u' && Py_TOLOWER(encoding[1]) == 't' && Py_TOLOWER(encoding[2]) == 'f') { encoding += 3; if (*encoding == '-' || *encoding == '_' ) encoding++; if (encoding[0] == '8' && encoding[1] == '\0') { *bytelength = 3; return ENC_UTF8; } else if (encoding[0] == '1' && encoding[1] == '6') { encoding += 2; *bytelength = 2; if (*encoding == '\0') { #ifdef WORDS_BIGENDIAN return ENC_UTF16BE; #else return ENC_UTF16LE; #endif } if (*encoding == '-' || *encoding == '_' ) encoding++; if (Py_TOLOWER(encoding[1]) == 'e' && encoding[2] == '\0') { if (Py_TOLOWER(encoding[0]) == 'b') return ENC_UTF16BE; if (Py_TOLOWER(encoding[0]) == 'l') return ENC_UTF16LE; } } else if (encoding[0] == '3' && encoding[1] == '2') { encoding += 2; *bytelength = 4; if (*encoding == '\0') { #ifdef WORDS_BIGENDIAN return ENC_UTF32BE; #else return ENC_UTF32LE; #endif } if (*encoding == '-' || *encoding == '_' ) encoding++; if (Py_TOLOWER(encoding[1]) == 'e' && encoding[2] == '\0') { if (Py_TOLOWER(encoding[0]) == 'b') return ENC_UTF32BE; if (Py_TOLOWER(encoding[0]) == 'l') return ENC_UTF32LE; } } } else if (strcmp(encoding, "CP_UTF8") == 0) { *bytelength = 3; return ENC_UTF8; } return ENC_UNKNOWN; } /* This handler is declared static until someone demonstrates a need to call it directly. */ static PyObject * PyCodec_SurrogatePassErrors(PyObject *exc) { PyObject *restuple; PyObject *object; PyObject *encode; char *encoding; int code; int bytelength; Py_ssize_t i; Py_ssize_t start; Py_ssize_t end; PyObject *res; if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) { unsigned char *outp; if (PyUnicodeEncodeError_GetStart(exc, &start)) return NULL; if (PyUnicodeEncodeError_GetEnd(exc, &end)) return NULL; if (!(object = PyUnicodeEncodeError_GetObject(exc))) return NULL; if (!(encode = PyUnicodeEncodeError_GetEncoding(exc))) { Py_DECREF(object); return NULL; } if (!(encoding = PyUnicode_AsUTF8(encode))) { Py_DECREF(object); Py_DECREF(encode); return NULL; } code = get_standard_encoding(encoding, &bytelength); Py_DECREF(encode); if (code == ENC_UNKNOWN) { /* Not supported, fail with original exception */ PyErr_SetObject(PyExceptionInstance_Class(exc), exc); Py_DECREF(object); return NULL; } if (end - start > PY_SSIZE_T_MAX / bytelength) end = start + PY_SSIZE_T_MAX / bytelength; res = PyBytes_FromStringAndSize(NULL, bytelength*(end-start)); if (!res) { Py_DECREF(object); return NULL; } outp = (unsigned char*)PyBytes_AsString(res); for (i = start; i < end; i++) { /* object is guaranteed to be "ready" */ Py_UCS4 ch = PyUnicode_READ_CHAR(object, i); if (!Py_UNICODE_IS_SURROGATE(ch)) { /* Not a surrogate, fail with original exception */ PyErr_SetObject(PyExceptionInstance_Class(exc), exc); Py_DECREF(res); Py_DECREF(object); return NULL; } switch (code) { case ENC_UTF8: *outp++ = (unsigned char)(0xe0 | (ch >> 12)); *outp++ = (unsigned char)(0x80 | ((ch >> 6) & 0x3f)); *outp++ = (unsigned char)(0x80 | (ch & 0x3f)); break; case ENC_UTF16LE: *outp++ = (unsigned char) ch; *outp++ = (unsigned char)(ch >> 8); break; case ENC_UTF16BE: *outp++ = (unsigned char)(ch >> 8); *outp++ = (unsigned char) ch; break; case ENC_UTF32LE: *outp++ = (unsigned char) ch; *outp++ = (unsigned char)(ch >> 8); *outp++ = (unsigned char)(ch >> 16); *outp++ = (unsigned char)(ch >> 24); break; case ENC_UTF32BE: *outp++ = (unsigned char)(ch >> 24); *outp++ = (unsigned char)(ch >> 16); *outp++ = (unsigned char)(ch >> 8); *outp++ = (unsigned char) ch; break; } } restuple = Py_BuildValue("(On)", res, end); Py_DECREF(res); Py_DECREF(object); return restuple; } else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeDecodeError)) { unsigned char *p; Py_UCS4 ch = 0; if (PyUnicodeDecodeError_GetStart(exc, &start)) return NULL; if (PyUnicodeDecodeError_GetEnd(exc, &end)) return NULL; if (!(object = PyUnicodeDecodeError_GetObject(exc))) return NULL; if (!(p = (unsigned char*)PyBytes_AsString(object))) { Py_DECREF(object); return NULL; } if (!(encode = PyUnicodeDecodeError_GetEncoding(exc))) { Py_DECREF(object); return NULL; } if (!(encoding = PyUnicode_AsUTF8(encode))) { Py_DECREF(object); Py_DECREF(encode); return NULL; } code = get_standard_encoding(encoding, &bytelength); Py_DECREF(encode); if (code == ENC_UNKNOWN) { /* Not supported, fail with original exception */ PyErr_SetObject(PyExceptionInstance_Class(exc), exc); Py_DECREF(object); return NULL; } /* Try decoding a single surrogate character. If there are more, let the codec call us again. */ p += start; if (PyBytes_GET_SIZE(object) - start >= bytelength) { switch (code) { case ENC_UTF8: if ((p[0] & 0xf0) == 0xe0 && (p[1] & 0xc0) == 0x80 && (p[2] & 0xc0) == 0x80) { /* it's a three-byte code */ ch = ((p[0] & 0x0f) << 12) + ((p[1] & 0x3f) << 6) + (p[2] & 0x3f); } break; case ENC_UTF16LE: ch = p[1] << 8 | p[0]; break; case ENC_UTF16BE: ch = p[0] << 8 | p[1]; break; case ENC_UTF32LE: ch = (p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]; break; case ENC_UTF32BE: ch = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]; break; } } Py_DECREF(object); if (!Py_UNICODE_IS_SURROGATE(ch)) { /* it's not a surrogate - fail */ PyErr_SetObject(PyExceptionInstance_Class(exc), exc); return NULL; } res = PyUnicode_FromOrdinal(ch); if (res == NULL) return NULL; return Py_BuildValue("(Nn)", res, start + bytelength); } else { wrong_exception_type(exc); return NULL; } } static PyObject * PyCodec_SurrogateEscapeErrors(PyObject *exc) { PyObject *restuple; PyObject *object; Py_ssize_t i; Py_ssize_t start; Py_ssize_t end; PyObject *res; if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeEncodeError)) { char *outp; if (PyUnicodeEncodeError_GetStart(exc, &start)) return NULL; if (PyUnicodeEncodeError_GetEnd(exc, &end)) return NULL; if (!(object = PyUnicodeEncodeError_GetObject(exc))) return NULL; res = PyBytes_FromStringAndSize(NULL, end-start); if (!res) { Py_DECREF(object); return NULL; } outp = PyBytes_AsString(res); for (i = start; i < end; i++) { /* object is guaranteed to be "ready" */ Py_UCS4 ch = PyUnicode_READ_CHAR(object, i); if (ch < 0xdc80 || ch > 0xdcff) { /* Not a UTF-8b surrogate, fail with original exception */ PyErr_SetObject(PyExceptionInstance_Class(exc), exc); Py_DECREF(res); Py_DECREF(object); return NULL; } *outp++ = ch - 0xdc00; } restuple = Py_BuildValue("(On)", res, end); Py_DECREF(res); Py_DECREF(object); return restuple; } else if (PyObject_TypeCheck(exc, (PyTypeObject *)PyExc_UnicodeDecodeError)) { PyObject *str; unsigned char *p; Py_UCS2 ch[4]; /* decode up to 4 bad bytes. */ int consumed = 0; if (PyUnicodeDecodeError_GetStart(exc, &start)) return NULL; if (PyUnicodeDecodeError_GetEnd(exc, &end)) return NULL; if (!(object = PyUnicodeDecodeError_GetObject(exc))) return NULL; if (!(p = (unsigned char*)PyBytes_AsString(object))) { Py_DECREF(object); return NULL; } while (consumed < 4 && consumed < end-start) { /* Refuse to escape ASCII bytes. */ if (p[start+consumed] < 128) break; ch[consumed] = 0xdc00 + p[start+consumed]; consumed++; } Py_DECREF(object); if (!consumed) { /* codec complained about ASCII byte. */ PyErr_SetObject(PyExceptionInstance_Class(exc), exc); return NULL; } str = PyUnicode_FromKindAndData(PyUnicode_2BYTE_KIND, ch, consumed); if (str == NULL) return NULL; return Py_BuildValue("(Nn)", str, start+consumed); } else { wrong_exception_type(exc); return NULL; } } static PyObject *strict_errors(PyObject *self, PyObject *exc) { return PyCodec_StrictErrors(exc); } static PyObject *ignore_errors(PyObject *self, PyObject *exc) { return PyCodec_IgnoreErrors(exc); } static PyObject *replace_errors(PyObject *self, PyObject *exc) { return PyCodec_ReplaceErrors(exc); } static PyObject *xmlcharrefreplace_errors(PyObject *self, PyObject *exc) { return PyCodec_XMLCharRefReplaceErrors(exc); } static PyObject *backslashreplace_errors(PyObject *self, PyObject *exc) { return PyCodec_BackslashReplaceErrors(exc); } static PyObject *namereplace_errors(PyObject *self, PyObject *exc) { return PyCodec_NameReplaceErrors(exc); } static PyObject *surrogatepass_errors(PyObject *self, PyObject *exc) { return PyCodec_SurrogatePassErrors(exc); } static PyObject *surrogateescape_errors(PyObject *self, PyObject *exc) { return PyCodec_SurrogateEscapeErrors(exc); } static int _PyCodecRegistry_Init(void) { static struct { char *name; PyMethodDef def; } methods[] = { { "strict", { "strict_errors", strict_errors, METH_O, PyDoc_STR("Implements the 'strict' error handling, which " "raises a UnicodeError on coding errors.") } }, { "ignore", { "ignore_errors", ignore_errors, METH_O, PyDoc_STR("Implements the 'ignore' error handling, which " "ignores malformed data and continues.") } }, { "replace", { "replace_errors", replace_errors, METH_O, PyDoc_STR("Implements the 'replace' error handling, which " "replaces malformed data with a replacement marker.") } }, { "xmlcharrefreplace", { "xmlcharrefreplace_errors", xmlcharrefreplace_errors, METH_O, PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, " "which replaces an unencodable character with the " "appropriate XML character reference.") } }, { "backslashreplace", { "backslashreplace_errors", backslashreplace_errors, METH_O, PyDoc_STR("Implements the 'backslashreplace' error handling, " "which replaces malformed data with a backslashed " "escape sequence.") } }, { "namereplace", { "namereplace_errors", namereplace_errors, METH_O, PyDoc_STR("Implements the 'namereplace' error handling, " "which replaces an unencodable character with a " "\\N{...} escape sequence.") } }, { "surrogatepass", { "surrogatepass", surrogatepass_errors, METH_O } }, { "surrogateescape", { "surrogateescape", surrogateescape_errors, METH_O } } }; PyInterpreterState *interp = PyThreadState_GET()->interp; PyObject *mod; unsigned i; if (interp->codec_search_path != NULL) return 0; interp->codec_search_path = PyList_New(0); interp->codec_search_cache = PyDict_New(); interp->codec_error_registry = PyDict_New(); if (interp->codec_error_registry) { for (i = 0; i < Py_ARRAY_LENGTH(methods); ++i) { PyObject *func = PyCFunction_NewEx(&methods[i].def, NULL, NULL); int res; if (!func) Py_FatalError("can't initialize codec error registry"); res = PyCodec_RegisterError(methods[i].name, func); Py_DECREF(func); if (res) Py_FatalError("can't initialize codec error registry"); } } if (interp->codec_search_path == NULL || interp->codec_search_cache == NULL || interp->codec_error_registry == NULL) Py_FatalError("can't initialize codec registry"); /* * XXX: terrible design! */ mod = PyImport_ImportModuleNoBlock("encodings"); if (mod == NULL) { return -1; } Py_DECREF(mod); interp->codecs_initialized = 1; return 0; }
47,667
1,570
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pyarena.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/mem/mem.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyarena.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/pymem.h" /* clang-format off */ /* A simple arena block structure. Measurements with standard library modules suggest the average allocation is about 20 bytes and that most compiles use a single block. TODO(jhylton): Think about a realloc API, maybe just for the last allocation? */ #define DEFAULT_BLOCK_SIZE 8192 #define ALIGNMENT 8 typedef struct _block { /* Total number of bytes owned by this block available to pass out. * Read-only after initialization. The first such byte starts at * ab_mem. */ size_t ab_size; /* Total number of bytes already passed out. The next byte available * to pass out starts at ab_mem + ab_offset. */ size_t ab_offset; /* An arena maintains a singly-linked, NULL-terminated list of * all blocks owned by the arena. These are linked via the * ab_next member. */ struct _block *ab_next; /* Pointer to the first allocatable byte owned by this block. Read- * only after initialization. */ void *ab_mem; } block; /* The arena manages two kinds of memory, blocks of raw memory and a list of PyObject* pointers. PyObjects are decrefed when the arena is freed. */ struct _arena { /* Pointer to the first block allocated for the arena, never NULL. It is used only to find the first block when the arena is being freed. */ block *a_head; /* Pointer to the block currently used for allocation. It's ab_next field should be NULL. If it is not-null after a call to block_alloc(), it means a new block has been allocated and a_cur should be reset to point it. */ block *a_cur; /* A Python list object containing references to all the PyObject pointers associated with this area. They will be DECREFed when the arena is freed. */ PyObject *a_objects; #if defined(Py_DEBUG) /* Debug output */ size_t total_allocs; size_t total_size; size_t total_blocks; size_t total_block_size; size_t total_big_blocks; #endif }; static block * block_new(size_t size) { /* Allocate header and block as one unit. ab_mem points just past header. */ block *b = (block *)PyMem_Malloc(sizeof(block) + size); if (!b) return NULL; b->ab_size = size; b->ab_mem = (void *)(b + 1); b->ab_next = NULL; b->ab_offset = (char *)_Py_ALIGN_UP(b->ab_mem, ALIGNMENT) - (char *)(b->ab_mem); return b; } static void block_free(block *b) { while (b) { block *next = b->ab_next; PyMem_Free(b); b = next; } } static void * block_alloc(block *b, size_t size) { void *p; assert(b); size = _Py_SIZE_ROUND_UP(size, ALIGNMENT); if (b->ab_offset + size > b->ab_size) { /* If we need to allocate more memory than will fit in the default block, allocate a one-off block that is exactly the right size. */ /* TODO(jhylton): Think about space waste at end of block */ block *newbl = block_new( size < DEFAULT_BLOCK_SIZE ? DEFAULT_BLOCK_SIZE : size); if (!newbl) return NULL; assert(!b->ab_next); b->ab_next = newbl; b = newbl; } assert(b->ab_offset + size <= b->ab_size); p = (void *)(((char *)b->ab_mem) + b->ab_offset); b->ab_offset += size; return p; } PyArena * PyArena_New() { PyArena* arena = (PyArena *)PyMem_Malloc(sizeof(PyArena)); if (!arena) return (PyArena*)PyErr_NoMemory(); arena->a_head = block_new(DEFAULT_BLOCK_SIZE); arena->a_cur = arena->a_head; if (!arena->a_head) { PyMem_Free((void *)arena); return (PyArena*)PyErr_NoMemory(); } arena->a_objects = PyList_New(0); if (!arena->a_objects) { block_free(arena->a_head); PyMem_Free((void *)arena); return (PyArena*)PyErr_NoMemory(); } #if defined(Py_DEBUG) arena->total_allocs = 0; arena->total_size = 0; arena->total_blocks = 1; arena->total_block_size = DEFAULT_BLOCK_SIZE; arena->total_big_blocks = 0; #endif return arena; } void PyArena_Free(PyArena *arena) { assert(arena); #if defined(Py_DEBUG) /* fprintf(stderr, "alloc=%d size=%d blocks=%d block_size=%d big=%d objects=%d\n", arena->total_allocs, arena->total_size, arena->total_blocks, arena->total_block_size, arena->total_big_blocks, PyList_Size(arena->a_objects)); */ #endif block_free(arena->a_head); /* This property normally holds, except when the code being compiled is sys.getobjects(0), in which case there will be two references. assert(arena->a_objects->ob_refcnt == 1); */ Py_DECREF(arena->a_objects); PyMem_Free(arena); } void * PyArena_Malloc(PyArena *arena, size_t size) { void *p = block_alloc(arena->a_cur, size); if (!p) return PyErr_NoMemory(); #if defined(Py_DEBUG) arena->total_allocs++; arena->total_size += size; #endif /* Reset cur if we allocated a new block. */ if (arena->a_cur->ab_next) { arena->a_cur = arena->a_cur->ab_next; #if defined(Py_DEBUG) arena->total_blocks++; arena->total_block_size += arena->a_cur->ab_size; if (arena->a_cur->ab_size > DEFAULT_BLOCK_SIZE) ++arena->total_big_blocks; #endif } return p; } int PyArena_AddPyObject(PyArena *arena, PyObject *obj) { int r = PyList_Append(arena->a_objects, obj); if (r >= 0) { Py_DECREF(obj); } return r; }
6,754
225
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/initialized.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/pylifecycle.h" int _Py_initialized; int Py_IsInitialized(void) { return _Py_initialized; }
948
14
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/graminit.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/grammar.h" #include "third_party/python/Include/pgenheaders.h" /* clang-format off */ /* Generated by Parser/pgen */ static arc arcs_0_0[3] = { {2, 1}, {3, 1}, {4, 2}, }; static arc arcs_0_1[1] = { {0, 1}, }; static arc arcs_0_2[1] = { {2, 1}, }; static state states_0[3] = { {.s_narcs=3, .s_arc=arcs_0_0}, {.s_narcs=1, .s_arc=arcs_0_1}, {.s_narcs=1, .s_arc=arcs_0_2}, }; static arc arcs_1_0[3] = { {2, 0}, {6, 0}, {7, 1}, }; static arc arcs_1_1[1] = { {0, 1}, }; static state states_1[2] = { {.s_narcs=3, .s_arc=arcs_1_0}, {.s_narcs=1, .s_arc=arcs_1_1}, }; static arc arcs_2_0[1] = { {9, 1}, }; static arc arcs_2_1[2] = { {2, 1}, {7, 2}, }; static arc arcs_2_2[1] = { {0, 2}, }; static state states_2[3] = { {.s_narcs=1, .s_arc=arcs_2_0}, {.s_narcs=2, .s_arc=arcs_2_1}, {.s_narcs=1, .s_arc=arcs_2_2}, }; static arc arcs_3_0[1] = { {11, 1}, }; static arc arcs_3_1[1] = { {12, 2}, }; static arc arcs_3_2[2] = { {13, 3}, {2, 4}, }; static arc arcs_3_3[2] = { {14, 5}, {15, 6}, }; static arc arcs_3_4[1] = { {0, 4}, }; static arc arcs_3_5[1] = { {15, 6}, }; static arc arcs_3_6[1] = { {2, 4}, }; static state states_3[7] = { {.s_narcs=1, .s_arc=arcs_3_0}, {.s_narcs=1, .s_arc=arcs_3_1}, {.s_narcs=2, .s_arc=arcs_3_2}, {.s_narcs=2, .s_arc=arcs_3_3}, {.s_narcs=1, .s_arc=arcs_3_4}, {.s_narcs=1, .s_arc=arcs_3_5}, {.s_narcs=1, .s_arc=arcs_3_6}, }; static arc arcs_4_0[1] = { {10, 1}, }; static arc arcs_4_1[2] = { {10, 1}, {0, 1}, }; static state states_4[2] = { {.s_narcs=1, .s_arc=arcs_4_0}, {.s_narcs=2, .s_arc=arcs_4_1}, }; static arc arcs_5_0[1] = { {16, 1}, }; static arc arcs_5_1[3] = { {18, 2}, {19, 2}, {20, 2}, }; static arc arcs_5_2[1] = { {0, 2}, }; static state states_5[3] = { {.s_narcs=1, .s_arc=arcs_5_0}, {.s_narcs=3, .s_arc=arcs_5_1}, {.s_narcs=1, .s_arc=arcs_5_2}, }; static arc arcs_6_0[1] = { {21, 1}, }; static arc arcs_6_1[1] = { {19, 2}, }; static arc arcs_6_2[1] = { {0, 2}, }; static state states_6[3] = { {.s_narcs=1, .s_arc=arcs_6_0}, {.s_narcs=1, .s_arc=arcs_6_1}, {.s_narcs=1, .s_arc=arcs_6_2}, }; static arc arcs_7_0[1] = { {22, 1}, }; static arc arcs_7_1[1] = { {23, 2}, }; static arc arcs_7_2[1] = { {24, 3}, }; static arc arcs_7_3[2] = { {25, 4}, {27, 5}, }; static arc arcs_7_4[1] = { {26, 6}, }; static arc arcs_7_5[1] = { {28, 7}, }; static arc arcs_7_6[1] = { {27, 5}, }; static arc arcs_7_7[1] = { {0, 7}, }; static state states_7[8] = { {.s_narcs=1, .s_arc=arcs_7_0}, {.s_narcs=1, .s_arc=arcs_7_1}, {.s_narcs=1, .s_arc=arcs_7_2}, {.s_narcs=2, .s_arc=arcs_7_3}, {.s_narcs=1, .s_arc=arcs_7_4}, {.s_narcs=1, .s_arc=arcs_7_5}, {.s_narcs=1, .s_arc=arcs_7_6}, {.s_narcs=1, .s_arc=arcs_7_7}, }; static arc arcs_8_0[1] = { {13, 1}, }; static arc arcs_8_1[2] = { {29, 2}, {15, 3}, }; static arc arcs_8_2[1] = { {15, 3}, }; static arc arcs_8_3[1] = { {0, 3}, }; static state states_8[4] = { {.s_narcs=1, .s_arc=arcs_8_0}, {.s_narcs=2, .s_arc=arcs_8_1}, {.s_narcs=1, .s_arc=arcs_8_2}, {.s_narcs=1, .s_arc=arcs_8_3}, }; static arc arcs_9_0[3] = { {30, 1}, {33, 2}, {34, 3}, }; static arc arcs_9_1[3] = { {31, 4}, {32, 5}, {0, 1}, }; static arc arcs_9_2[3] = { {30, 6}, {32, 7}, {0, 2}, }; static arc arcs_9_3[1] = { {30, 8}, }; static arc arcs_9_4[1] = { {26, 9}, }; static arc arcs_9_5[4] = { {30, 10}, {33, 11}, {34, 3}, {0, 5}, }; static arc arcs_9_6[2] = { {32, 7}, {0, 6}, }; static arc arcs_9_7[3] = { {30, 12}, {34, 3}, {0, 7}, }; static arc arcs_9_8[2] = { {32, 13}, {0, 8}, }; static arc arcs_9_9[2] = { {32, 5}, {0, 9}, }; static arc arcs_9_10[3] = { {32, 5}, {31, 4}, {0, 10}, }; static arc arcs_9_11[3] = { {30, 14}, {32, 15}, {0, 11}, }; static arc arcs_9_12[3] = { {32, 7}, {31, 16}, {0, 12}, }; static arc arcs_9_13[1] = { {0, 13}, }; static arc arcs_9_14[2] = { {32, 15}, {0, 14}, }; static arc arcs_9_15[3] = { {30, 17}, {34, 3}, {0, 15}, }; static arc arcs_9_16[1] = { {26, 6}, }; static arc arcs_9_17[3] = { {32, 15}, {31, 18}, {0, 17}, }; static arc arcs_9_18[1] = { {26, 14}, }; static state states_9[19] = { {.s_narcs=3, .s_arc=arcs_9_0}, {.s_narcs=3, .s_arc=arcs_9_1}, {.s_narcs=3, .s_arc=arcs_9_2}, {.s_narcs=1, .s_arc=arcs_9_3}, {.s_narcs=1, .s_arc=arcs_9_4}, {.s_narcs=4, .s_arc=arcs_9_5}, {.s_narcs=2, .s_arc=arcs_9_6}, {.s_narcs=3, .s_arc=arcs_9_7}, {.s_narcs=2, .s_arc=arcs_9_8}, {.s_narcs=2, .s_arc=arcs_9_9}, {.s_narcs=3, .s_arc=arcs_9_10}, {.s_narcs=3, .s_arc=arcs_9_11}, {.s_narcs=3, .s_arc=arcs_9_12}, {.s_narcs=1, .s_arc=arcs_9_13}, {.s_narcs=2, .s_arc=arcs_9_14}, {.s_narcs=3, .s_arc=arcs_9_15}, {.s_narcs=1, .s_arc=arcs_9_16}, {.s_narcs=3, .s_arc=arcs_9_17}, {.s_narcs=1, .s_arc=arcs_9_18}, }; static arc arcs_10_0[1] = { {23, 1}, }; static arc arcs_10_1[2] = { {27, 2}, {0, 1}, }; static arc arcs_10_2[1] = { {26, 3}, }; static arc arcs_10_3[1] = { {0, 3}, }; static state states_10[4] = { {.s_narcs=1, .s_arc=arcs_10_0}, {.s_narcs=2, .s_arc=arcs_10_1}, {.s_narcs=1, .s_arc=arcs_10_2}, {.s_narcs=1, .s_arc=arcs_10_3}, }; static arc arcs_11_0[3] = { {36, 1}, {33, 2}, {34, 3}, }; static arc arcs_11_1[3] = { {31, 4}, {32, 5}, {0, 1}, }; static arc arcs_11_2[3] = { {36, 6}, {32, 7}, {0, 2}, }; static arc arcs_11_3[1] = { {36, 8}, }; static arc arcs_11_4[1] = { {26, 9}, }; static arc arcs_11_5[4] = { {36, 10}, {33, 11}, {34, 3}, {0, 5}, }; static arc arcs_11_6[2] = { {32, 7}, {0, 6}, }; static arc arcs_11_7[3] = { {36, 12}, {34, 3}, {0, 7}, }; static arc arcs_11_8[2] = { {32, 13}, {0, 8}, }; static arc arcs_11_9[2] = { {32, 5}, {0, 9}, }; static arc arcs_11_10[3] = { {32, 5}, {31, 4}, {0, 10}, }; static arc arcs_11_11[3] = { {36, 14}, {32, 15}, {0, 11}, }; static arc arcs_11_12[3] = { {32, 7}, {31, 16}, {0, 12}, }; static arc arcs_11_13[1] = { {0, 13}, }; static arc arcs_11_14[2] = { {32, 15}, {0, 14}, }; static arc arcs_11_15[3] = { {36, 17}, {34, 3}, {0, 15}, }; static arc arcs_11_16[1] = { {26, 6}, }; static arc arcs_11_17[3] = { {32, 15}, {31, 18}, {0, 17}, }; static arc arcs_11_18[1] = { {26, 14}, }; static state states_11[19] = { {.s_narcs=3, .s_arc=arcs_11_0}, {.s_narcs=3, .s_arc=arcs_11_1}, {.s_narcs=3, .s_arc=arcs_11_2}, {.s_narcs=1, .s_arc=arcs_11_3}, {.s_narcs=1, .s_arc=arcs_11_4}, {.s_narcs=4, .s_arc=arcs_11_5}, {.s_narcs=2, .s_arc=arcs_11_6}, {.s_narcs=3, .s_arc=arcs_11_7}, {.s_narcs=2, .s_arc=arcs_11_8}, {.s_narcs=2, .s_arc=arcs_11_9}, {.s_narcs=3, .s_arc=arcs_11_10}, {.s_narcs=3, .s_arc=arcs_11_11}, {.s_narcs=3, .s_arc=arcs_11_12}, {.s_narcs=1, .s_arc=arcs_11_13}, {.s_narcs=2, .s_arc=arcs_11_14}, {.s_narcs=3, .s_arc=arcs_11_15}, {.s_narcs=1, .s_arc=arcs_11_16}, {.s_narcs=3, .s_arc=arcs_11_17}, {.s_narcs=1, .s_arc=arcs_11_18}, }; static arc arcs_12_0[1] = { {23, 1}, }; static arc arcs_12_1[1] = { {0, 1}, }; static state states_12[2] = { {.s_narcs=1, .s_arc=arcs_12_0}, {.s_narcs=1, .s_arc=arcs_12_1}, }; static arc arcs_13_0[2] = { {3, 1}, {4, 1}, }; static arc arcs_13_1[1] = { {0, 1}, }; static state states_13[2] = { {.s_narcs=2, .s_arc=arcs_13_0}, {.s_narcs=1, .s_arc=arcs_13_1}, }; static arc arcs_14_0[1] = { {37, 1}, }; static arc arcs_14_1[2] = { {38, 2}, {2, 3}, }; static arc arcs_14_2[2] = { {37, 1}, {2, 3}, }; static arc arcs_14_3[1] = { {0, 3}, }; static state states_14[4] = { {.s_narcs=1, .s_arc=arcs_14_0}, {.s_narcs=2, .s_arc=arcs_14_1}, {.s_narcs=2, .s_arc=arcs_14_2}, {.s_narcs=1, .s_arc=arcs_14_3}, }; static arc arcs_15_0[8] = { {39, 1}, {40, 1}, {41, 1}, {42, 1}, {43, 1}, {44, 1}, {45, 1}, {46, 1}, }; static arc arcs_15_1[1] = { {0, 1}, }; static state states_15[2] = { {.s_narcs=8, .s_arc=arcs_15_0}, {.s_narcs=1, .s_arc=arcs_15_1}, }; static arc arcs_16_0[1] = { {47, 1}, }; static arc arcs_16_1[4] = { {48, 2}, {49, 3}, {31, 4}, {0, 1}, }; static arc arcs_16_2[1] = { {0, 2}, }; static arc arcs_16_3[2] = { {50, 2}, {9, 2}, }; static arc arcs_16_4[2] = { {50, 5}, {47, 5}, }; static arc arcs_16_5[2] = { {31, 4}, {0, 5}, }; static state states_16[6] = { {.s_narcs=1, .s_arc=arcs_16_0}, {.s_narcs=4, .s_arc=arcs_16_1}, {.s_narcs=1, .s_arc=arcs_16_2}, {.s_narcs=2, .s_arc=arcs_16_3}, {.s_narcs=2, .s_arc=arcs_16_4}, {.s_narcs=2, .s_arc=arcs_16_5}, }; static arc arcs_17_0[1] = { {27, 1}, }; static arc arcs_17_1[1] = { {26, 2}, }; static arc arcs_17_2[2] = { {31, 3}, {0, 2}, }; static arc arcs_17_3[1] = { {26, 4}, }; static arc arcs_17_4[1] = { {0, 4}, }; static state states_17[5] = { {.s_narcs=1, .s_arc=arcs_17_0}, {.s_narcs=1, .s_arc=arcs_17_1}, {.s_narcs=2, .s_arc=arcs_17_2}, {.s_narcs=1, .s_arc=arcs_17_3}, {.s_narcs=1, .s_arc=arcs_17_4}, }; static arc arcs_18_0[2] = { {26, 1}, {51, 1}, }; static arc arcs_18_1[2] = { {32, 2}, {0, 1}, }; static arc arcs_18_2[3] = { {26, 1}, {51, 1}, {0, 2}, }; static state states_18[3] = { {.s_narcs=2, .s_arc=arcs_18_0}, {.s_narcs=2, .s_arc=arcs_18_1}, {.s_narcs=3, .s_arc=arcs_18_2}, }; static arc arcs_19_0[13] = { {52, 1}, {53, 1}, {54, 1}, {55, 1}, {56, 1}, {57, 1}, {58, 1}, {59, 1}, {60, 1}, {61, 1}, {62, 1}, {63, 1}, {64, 1}, }; static arc arcs_19_1[1] = { {0, 1}, }; static state states_19[2] = { {.s_narcs=13, .s_arc=arcs_19_0}, {.s_narcs=1, .s_arc=arcs_19_1}, }; static arc arcs_20_0[1] = { {65, 1}, }; static arc arcs_20_1[1] = { {66, 2}, }; static arc arcs_20_2[1] = { {0, 2}, }; static state states_20[3] = { {.s_narcs=1, .s_arc=arcs_20_0}, {.s_narcs=1, .s_arc=arcs_20_1}, {.s_narcs=1, .s_arc=arcs_20_2}, }; static arc arcs_21_0[1] = { {67, 1}, }; static arc arcs_21_1[1] = { {0, 1}, }; static state states_21[2] = { {.s_narcs=1, .s_arc=arcs_21_0}, {.s_narcs=1, .s_arc=arcs_21_1}, }; static arc arcs_22_0[5] = { {68, 1}, {69, 1}, {70, 1}, {71, 1}, {72, 1}, }; static arc arcs_22_1[1] = { {0, 1}, }; static state states_22[2] = { {.s_narcs=5, .s_arc=arcs_22_0}, {.s_narcs=1, .s_arc=arcs_22_1}, }; static arc arcs_23_0[1] = { {73, 1}, }; static arc arcs_23_1[1] = { {0, 1}, }; static state states_23[2] = { {.s_narcs=1, .s_arc=arcs_23_0}, {.s_narcs=1, .s_arc=arcs_23_1}, }; static arc arcs_24_0[1] = { {74, 1}, }; static arc arcs_24_1[1] = { {0, 1}, }; static state states_24[2] = { {.s_narcs=1, .s_arc=arcs_24_0}, {.s_narcs=1, .s_arc=arcs_24_1}, }; static arc arcs_25_0[1] = { {75, 1}, }; static arc arcs_25_1[2] = { {9, 2}, {0, 1}, }; static arc arcs_25_2[1] = { {0, 2}, }; static state states_25[3] = { {.s_narcs=1, .s_arc=arcs_25_0}, {.s_narcs=2, .s_arc=arcs_25_1}, {.s_narcs=1, .s_arc=arcs_25_2}, }; static arc arcs_26_0[1] = { {50, 1}, }; static arc arcs_26_1[1] = { {0, 1}, }; static state states_26[2] = { {.s_narcs=1, .s_arc=arcs_26_0}, {.s_narcs=1, .s_arc=arcs_26_1}, }; static arc arcs_27_0[1] = { {76, 1}, }; static arc arcs_27_1[2] = { {26, 2}, {0, 1}, }; static arc arcs_27_2[2] = { {77, 3}, {0, 2}, }; static arc arcs_27_3[1] = { {26, 4}, }; static arc arcs_27_4[1] = { {0, 4}, }; static state states_27[5] = { {.s_narcs=1, .s_arc=arcs_27_0}, {.s_narcs=2, .s_arc=arcs_27_1}, {.s_narcs=2, .s_arc=arcs_27_2}, {.s_narcs=1, .s_arc=arcs_27_3}, {.s_narcs=1, .s_arc=arcs_27_4}, }; static arc arcs_28_0[2] = { {78, 1}, {79, 1}, }; static arc arcs_28_1[1] = { {0, 1}, }; static state states_28[2] = { {.s_narcs=2, .s_arc=arcs_28_0}, {.s_narcs=1, .s_arc=arcs_28_1}, }; static arc arcs_29_0[1] = { {80, 1}, }; static arc arcs_29_1[1] = { {81, 2}, }; static arc arcs_29_2[1] = { {0, 2}, }; static state states_29[3] = { {.s_narcs=1, .s_arc=arcs_29_0}, {.s_narcs=1, .s_arc=arcs_29_1}, {.s_narcs=1, .s_arc=arcs_29_2}, }; static arc arcs_30_0[1] = { {77, 1}, }; static arc arcs_30_1[3] = { {82, 2}, {83, 2}, {12, 3}, }; static arc arcs_30_2[4] = { {82, 2}, {83, 2}, {12, 3}, {80, 4}, }; static arc arcs_30_3[1] = { {80, 4}, }; static arc arcs_30_4[3] = { {33, 5}, {13, 6}, {84, 5}, }; static arc arcs_30_5[1] = { {0, 5}, }; static arc arcs_30_6[1] = { {84, 7}, }; static arc arcs_30_7[1] = { {15, 5}, }; static state states_30[8] = { {.s_narcs=1, .s_arc=arcs_30_0}, {.s_narcs=3, .s_arc=arcs_30_1}, {.s_narcs=4, .s_arc=arcs_30_2}, {.s_narcs=1, .s_arc=arcs_30_3}, {.s_narcs=3, .s_arc=arcs_30_4}, {.s_narcs=1, .s_arc=arcs_30_5}, {.s_narcs=1, .s_arc=arcs_30_6}, {.s_narcs=1, .s_arc=arcs_30_7}, }; static arc arcs_31_0[1] = { {23, 1}, }; static arc arcs_31_1[2] = { {86, 2}, {0, 1}, }; static arc arcs_31_2[1] = { {23, 3}, }; static arc arcs_31_3[1] = { {0, 3}, }; static state states_31[4] = { {.s_narcs=1, .s_arc=arcs_31_0}, {.s_narcs=2, .s_arc=arcs_31_1}, {.s_narcs=1, .s_arc=arcs_31_2}, {.s_narcs=1, .s_arc=arcs_31_3}, }; static arc arcs_32_0[1] = { {12, 1}, }; static arc arcs_32_1[2] = { {86, 2}, {0, 1}, }; static arc arcs_32_2[1] = { {23, 3}, }; static arc arcs_32_3[1] = { {0, 3}, }; static state states_32[4] = { {.s_narcs=1, .s_arc=arcs_32_0}, {.s_narcs=2, .s_arc=arcs_32_1}, {.s_narcs=1, .s_arc=arcs_32_2}, {.s_narcs=1, .s_arc=arcs_32_3}, }; static arc arcs_33_0[1] = { {85, 1}, }; static arc arcs_33_1[2] = { {32, 2}, {0, 1}, }; static arc arcs_33_2[2] = { {85, 1}, {0, 2}, }; static state states_33[3] = { {.s_narcs=1, .s_arc=arcs_33_0}, {.s_narcs=2, .s_arc=arcs_33_1}, {.s_narcs=2, .s_arc=arcs_33_2}, }; static arc arcs_34_0[1] = { {87, 1}, }; static arc arcs_34_1[2] = { {32, 0}, {0, 1}, }; static state states_34[2] = { {.s_narcs=1, .s_arc=arcs_34_0}, {.s_narcs=2, .s_arc=arcs_34_1}, }; static arc arcs_35_0[1] = { {23, 1}, }; static arc arcs_35_1[2] = { {82, 0}, {0, 1}, }; static state states_35[2] = { {.s_narcs=1, .s_arc=arcs_35_0}, {.s_narcs=2, .s_arc=arcs_35_1}, }; static arc arcs_36_0[1] = { {88, 1}, }; static arc arcs_36_1[1] = { {23, 2}, }; static arc arcs_36_2[2] = { {32, 1}, {0, 2}, }; static state states_36[3] = { {.s_narcs=1, .s_arc=arcs_36_0}, {.s_narcs=1, .s_arc=arcs_36_1}, {.s_narcs=2, .s_arc=arcs_36_2}, }; static arc arcs_37_0[1] = { {89, 1}, }; static arc arcs_37_1[1] = { {23, 2}, }; static arc arcs_37_2[2] = { {32, 1}, {0, 2}, }; static state states_37[3] = { {.s_narcs=1, .s_arc=arcs_37_0}, {.s_narcs=1, .s_arc=arcs_37_1}, {.s_narcs=2, .s_arc=arcs_37_2}, }; static arc arcs_38_0[1] = { {90, 1}, }; static arc arcs_38_1[1] = { {26, 2}, }; static arc arcs_38_2[2] = { {32, 3}, {0, 2}, }; static arc arcs_38_3[1] = { {26, 4}, }; static arc arcs_38_4[1] = { {0, 4}, }; static state states_38[5] = { {.s_narcs=1, .s_arc=arcs_38_0}, {.s_narcs=1, .s_arc=arcs_38_1}, {.s_narcs=2, .s_arc=arcs_38_2}, {.s_narcs=1, .s_arc=arcs_38_3}, {.s_narcs=1, .s_arc=arcs_38_4}, }; static arc arcs_39_0[9] = { {91, 1}, {92, 1}, {93, 1}, {94, 1}, {95, 1}, {19, 1}, {18, 1}, {17, 1}, {96, 1}, }; static arc arcs_39_1[1] = { {0, 1}, }; static state states_39[2] = { {.s_narcs=9, .s_arc=arcs_39_0}, {.s_narcs=1, .s_arc=arcs_39_1}, }; static arc arcs_40_0[1] = { {21, 1}, }; static arc arcs_40_1[3] = { {19, 2}, {95, 2}, {93, 2}, }; static arc arcs_40_2[1] = { {0, 2}, }; static state states_40[3] = { {.s_narcs=1, .s_arc=arcs_40_0}, {.s_narcs=3, .s_arc=arcs_40_1}, {.s_narcs=1, .s_arc=arcs_40_2}, }; static arc arcs_41_0[1] = { {97, 1}, }; static arc arcs_41_1[1] = { {26, 2}, }; static arc arcs_41_2[1] = { {27, 3}, }; static arc arcs_41_3[1] = { {28, 4}, }; static arc arcs_41_4[3] = { {98, 1}, {99, 5}, {0, 4}, }; static arc arcs_41_5[1] = { {27, 6}, }; static arc arcs_41_6[1] = { {28, 7}, }; static arc arcs_41_7[1] = { {0, 7}, }; static state states_41[8] = { {.s_narcs=1, .s_arc=arcs_41_0}, {.s_narcs=1, .s_arc=arcs_41_1}, {.s_narcs=1, .s_arc=arcs_41_2}, {.s_narcs=1, .s_arc=arcs_41_3}, {.s_narcs=3, .s_arc=arcs_41_4}, {.s_narcs=1, .s_arc=arcs_41_5}, {.s_narcs=1, .s_arc=arcs_41_6}, {.s_narcs=1, .s_arc=arcs_41_7}, }; static arc arcs_42_0[1] = { {100, 1}, }; static arc arcs_42_1[1] = { {26, 2}, }; static arc arcs_42_2[1] = { {27, 3}, }; static arc arcs_42_3[1] = { {28, 4}, }; static arc arcs_42_4[2] = { {99, 5}, {0, 4}, }; static arc arcs_42_5[1] = { {27, 6}, }; static arc arcs_42_6[1] = { {28, 7}, }; static arc arcs_42_7[1] = { {0, 7}, }; static state states_42[8] = { {.s_narcs=1, .s_arc=arcs_42_0}, {.s_narcs=1, .s_arc=arcs_42_1}, {.s_narcs=1, .s_arc=arcs_42_2}, {.s_narcs=1, .s_arc=arcs_42_3}, {.s_narcs=2, .s_arc=arcs_42_4}, {.s_narcs=1, .s_arc=arcs_42_5}, {.s_narcs=1, .s_arc=arcs_42_6}, {.s_narcs=1, .s_arc=arcs_42_7}, }; static arc arcs_43_0[1] = { {101, 1}, }; static arc arcs_43_1[1] = { {66, 2}, }; static arc arcs_43_2[1] = { {102, 3}, }; static arc arcs_43_3[1] = { {9, 4}, }; static arc arcs_43_4[1] = { {27, 5}, }; static arc arcs_43_5[1] = { {28, 6}, }; static arc arcs_43_6[2] = { {99, 7}, {0, 6}, }; static arc arcs_43_7[1] = { {27, 8}, }; static arc arcs_43_8[1] = { {28, 9}, }; static arc arcs_43_9[1] = { {0, 9}, }; static state states_43[10] = { {.s_narcs=1, .s_arc=arcs_43_0}, {.s_narcs=1, .s_arc=arcs_43_1}, {.s_narcs=1, .s_arc=arcs_43_2}, {.s_narcs=1, .s_arc=arcs_43_3}, {.s_narcs=1, .s_arc=arcs_43_4}, {.s_narcs=1, .s_arc=arcs_43_5}, {.s_narcs=2, .s_arc=arcs_43_6}, {.s_narcs=1, .s_arc=arcs_43_7}, {.s_narcs=1, .s_arc=arcs_43_8}, {.s_narcs=1, .s_arc=arcs_43_9}, }; static arc arcs_44_0[1] = { {103, 1}, }; static arc arcs_44_1[1] = { {27, 2}, }; static arc arcs_44_2[1] = { {28, 3}, }; static arc arcs_44_3[2] = { {104, 4}, {105, 5}, }; static arc arcs_44_4[1] = { {27, 6}, }; static arc arcs_44_5[1] = { {27, 7}, }; static arc arcs_44_6[1] = { {28, 8}, }; static arc arcs_44_7[1] = { {28, 9}, }; static arc arcs_44_8[4] = { {104, 4}, {99, 10}, {105, 5}, {0, 8}, }; static arc arcs_44_9[1] = { {0, 9}, }; static arc arcs_44_10[1] = { {27, 11}, }; static arc arcs_44_11[1] = { {28, 12}, }; static arc arcs_44_12[2] = { {105, 5}, {0, 12}, }; static state states_44[13] = { {.s_narcs=1, .s_arc=arcs_44_0}, {.s_narcs=1, .s_arc=arcs_44_1}, {.s_narcs=1, .s_arc=arcs_44_2}, {.s_narcs=2, .s_arc=arcs_44_3}, {.s_narcs=1, .s_arc=arcs_44_4}, {.s_narcs=1, .s_arc=arcs_44_5}, {.s_narcs=1, .s_arc=arcs_44_6}, {.s_narcs=1, .s_arc=arcs_44_7}, {.s_narcs=4, .s_arc=arcs_44_8}, {.s_narcs=1, .s_arc=arcs_44_9}, {.s_narcs=1, .s_arc=arcs_44_10}, {.s_narcs=1, .s_arc=arcs_44_11}, {.s_narcs=2, .s_arc=arcs_44_12}, }; static arc arcs_45_0[1] = { {106, 1}, }; static arc arcs_45_1[1] = { {107, 2}, }; static arc arcs_45_2[2] = { {32, 1}, {27, 3}, }; static arc arcs_45_3[1] = { {28, 4}, }; static arc arcs_45_4[1] = { {0, 4}, }; static state states_45[5] = { {.s_narcs=1, .s_arc=arcs_45_0}, {.s_narcs=1, .s_arc=arcs_45_1}, {.s_narcs=2, .s_arc=arcs_45_2}, {.s_narcs=1, .s_arc=arcs_45_3}, {.s_narcs=1, .s_arc=arcs_45_4}, }; static arc arcs_46_0[1] = { {26, 1}, }; static arc arcs_46_1[2] = { {86, 2}, {0, 1}, }; static arc arcs_46_2[1] = { {108, 3}, }; static arc arcs_46_3[1] = { {0, 3}, }; static state states_46[4] = { {.s_narcs=1, .s_arc=arcs_46_0}, {.s_narcs=2, .s_arc=arcs_46_1}, {.s_narcs=1, .s_arc=arcs_46_2}, {.s_narcs=1, .s_arc=arcs_46_3}, }; static arc arcs_47_0[1] = { {109, 1}, }; static arc arcs_47_1[2] = { {26, 2}, {0, 1}, }; static arc arcs_47_2[2] = { {86, 3}, {0, 2}, }; static arc arcs_47_3[1] = { {23, 4}, }; static arc arcs_47_4[1] = { {0, 4}, }; static state states_47[5] = { {.s_narcs=1, .s_arc=arcs_47_0}, {.s_narcs=2, .s_arc=arcs_47_1}, {.s_narcs=2, .s_arc=arcs_47_2}, {.s_narcs=1, .s_arc=arcs_47_3}, {.s_narcs=1, .s_arc=arcs_47_4}, }; static arc arcs_48_0[2] = { {3, 1}, {2, 2}, }; static arc arcs_48_1[1] = { {0, 1}, }; static arc arcs_48_2[1] = { {110, 3}, }; static arc arcs_48_3[1] = { {6, 4}, }; static arc arcs_48_4[2] = { {6, 4}, {111, 1}, }; static state states_48[5] = { {.s_narcs=2, .s_arc=arcs_48_0}, {.s_narcs=1, .s_arc=arcs_48_1}, {.s_narcs=1, .s_arc=arcs_48_2}, {.s_narcs=1, .s_arc=arcs_48_3}, {.s_narcs=2, .s_arc=arcs_48_4}, }; static arc arcs_49_0[2] = { {112, 1}, {113, 2}, }; static arc arcs_49_1[2] = { {97, 3}, {0, 1}, }; static arc arcs_49_2[1] = { {0, 2}, }; static arc arcs_49_3[1] = { {112, 4}, }; static arc arcs_49_4[1] = { {99, 5}, }; static arc arcs_49_5[1] = { {26, 2}, }; static state states_49[6] = { {.s_narcs=2, .s_arc=arcs_49_0}, {.s_narcs=2, .s_arc=arcs_49_1}, {.s_narcs=1, .s_arc=arcs_49_2}, {.s_narcs=1, .s_arc=arcs_49_3}, {.s_narcs=1, .s_arc=arcs_49_4}, {.s_narcs=1, .s_arc=arcs_49_5}, }; static arc arcs_50_0[2] = { {112, 1}, {115, 1}, }; static arc arcs_50_1[1] = { {0, 1}, }; static state states_50[2] = { {.s_narcs=2, .s_arc=arcs_50_0}, {.s_narcs=1, .s_arc=arcs_50_1}, }; static arc arcs_51_0[1] = { {116, 1}, }; static arc arcs_51_1[2] = { {35, 2}, {27, 3}, }; static arc arcs_51_2[1] = { {27, 3}, }; static arc arcs_51_3[1] = { {26, 4}, }; static arc arcs_51_4[1] = { {0, 4}, }; static state states_51[5] = { {.s_narcs=1, .s_arc=arcs_51_0}, {.s_narcs=2, .s_arc=arcs_51_1}, {.s_narcs=1, .s_arc=arcs_51_2}, {.s_narcs=1, .s_arc=arcs_51_3}, {.s_narcs=1, .s_arc=arcs_51_4}, }; static arc arcs_52_0[1] = { {116, 1}, }; static arc arcs_52_1[2] = { {35, 2}, {27, 3}, }; static arc arcs_52_2[1] = { {27, 3}, }; static arc arcs_52_3[1] = { {114, 4}, }; static arc arcs_52_4[1] = { {0, 4}, }; static state states_52[5] = { {.s_narcs=1, .s_arc=arcs_52_0}, {.s_narcs=2, .s_arc=arcs_52_1}, {.s_narcs=1, .s_arc=arcs_52_2}, {.s_narcs=1, .s_arc=arcs_52_3}, {.s_narcs=1, .s_arc=arcs_52_4}, }; static arc arcs_53_0[1] = { {117, 1}, }; static arc arcs_53_1[2] = { {118, 0}, {0, 1}, }; static state states_53[2] = { {.s_narcs=1, .s_arc=arcs_53_0}, {.s_narcs=2, .s_arc=arcs_53_1}, }; static arc arcs_54_0[1] = { {119, 1}, }; static arc arcs_54_1[2] = { {120, 0}, {0, 1}, }; static state states_54[2] = { {.s_narcs=1, .s_arc=arcs_54_0}, {.s_narcs=2, .s_arc=arcs_54_1}, }; static arc arcs_55_0[2] = { {121, 1}, {122, 2}, }; static arc arcs_55_1[1] = { {119, 2}, }; static arc arcs_55_2[1] = { {0, 2}, }; static state states_55[3] = { {.s_narcs=2, .s_arc=arcs_55_0}, {.s_narcs=1, .s_arc=arcs_55_1}, {.s_narcs=1, .s_arc=arcs_55_2}, }; static arc arcs_56_0[1] = { {108, 1}, }; static arc arcs_56_1[2] = { {123, 0}, {0, 1}, }; static state states_56[2] = { {.s_narcs=1, .s_arc=arcs_56_0}, {.s_narcs=2, .s_arc=arcs_56_1}, }; static arc arcs_57_0[10] = { {124, 1}, {125, 1}, {126, 1}, {127, 1}, {128, 1}, {129, 1}, {130, 1}, {102, 1}, {121, 2}, {131, 3}, }; static arc arcs_57_1[1] = { {0, 1}, }; static arc arcs_57_2[1] = { {102, 1}, }; static arc arcs_57_3[2] = { {121, 1}, {0, 3}, }; static state states_57[4] = { {.s_narcs=10, .s_arc=arcs_57_0}, {.s_narcs=1, .s_arc=arcs_57_1}, {.s_narcs=1, .s_arc=arcs_57_2}, {.s_narcs=2, .s_arc=arcs_57_3}, }; static arc arcs_58_0[1] = { {33, 1}, }; static arc arcs_58_1[1] = { {108, 2}, }; static arc arcs_58_2[1] = { {0, 2}, }; static state states_58[3] = { {.s_narcs=1, .s_arc=arcs_58_0}, {.s_narcs=1, .s_arc=arcs_58_1}, {.s_narcs=1, .s_arc=arcs_58_2}, }; static arc arcs_59_0[1] = { {132, 1}, }; static arc arcs_59_1[2] = { {133, 0}, {0, 1}, }; static state states_59[2] = { {.s_narcs=1, .s_arc=arcs_59_0}, {.s_narcs=2, .s_arc=arcs_59_1}, }; static arc arcs_60_0[1] = { {134, 1}, }; static arc arcs_60_1[2] = { {135, 0}, {0, 1}, }; static state states_60[2] = { {.s_narcs=1, .s_arc=arcs_60_0}, {.s_narcs=2, .s_arc=arcs_60_1}, }; static arc arcs_61_0[1] = { {136, 1}, }; static arc arcs_61_1[2] = { {137, 0}, {0, 1}, }; static state states_61[2] = { {.s_narcs=1, .s_arc=arcs_61_0}, {.s_narcs=2, .s_arc=arcs_61_1}, }; static arc arcs_62_0[1] = { {138, 1}, }; static arc arcs_62_1[3] = { {139, 0}, {140, 0}, {0, 1}, }; static state states_62[2] = { {.s_narcs=1, .s_arc=arcs_62_0}, {.s_narcs=3, .s_arc=arcs_62_1}, }; static arc arcs_63_0[1] = { {141, 1}, }; static arc arcs_63_1[3] = { {142, 0}, {143, 0}, {0, 1}, }; static state states_63[2] = { {.s_narcs=1, .s_arc=arcs_63_0}, {.s_narcs=3, .s_arc=arcs_63_1}, }; static arc arcs_64_0[1] = { {144, 1}, }; static arc arcs_64_1[6] = { {33, 0}, {11, 0}, {145, 0}, {146, 0}, {147, 0}, {0, 1}, }; static state states_64[2] = { {.s_narcs=1, .s_arc=arcs_64_0}, {.s_narcs=6, .s_arc=arcs_64_1}, }; static arc arcs_65_0[4] = { {142, 1}, {143, 1}, {148, 1}, {149, 2}, }; static arc arcs_65_1[1] = { {144, 2}, }; static arc arcs_65_2[1] = { {0, 2}, }; static state states_65[3] = { {.s_narcs=4, .s_arc=arcs_65_0}, {.s_narcs=1, .s_arc=arcs_65_1}, {.s_narcs=1, .s_arc=arcs_65_2}, }; static arc arcs_66_0[1] = { {150, 1}, }; static arc arcs_66_1[2] = { {34, 2}, {0, 1}, }; static arc arcs_66_2[1] = { {144, 3}, }; static arc arcs_66_3[1] = { {0, 3}, }; static state states_66[4] = { {.s_narcs=1, .s_arc=arcs_66_0}, {.s_narcs=2, .s_arc=arcs_66_1}, {.s_narcs=1, .s_arc=arcs_66_2}, {.s_narcs=1, .s_arc=arcs_66_3}, }; static arc arcs_67_0[2] = { {151, 1}, {152, 2}, }; static arc arcs_67_1[1] = { {152, 2}, }; static arc arcs_67_2[2] = { {153, 2}, {0, 2}, }; static state states_67[3] = { {.s_narcs=2, .s_arc=arcs_67_0}, {.s_narcs=1, .s_arc=arcs_67_1}, {.s_narcs=2, .s_arc=arcs_67_2}, }; static arc arcs_68_0[10] = { {13, 1}, {155, 2}, {157, 3}, {23, 4}, {160, 4}, {161, 5}, {83, 4}, {162, 4}, {163, 4}, {164, 4}, }; static arc arcs_68_1[3] = { {50, 6}, {154, 6}, {15, 4}, }; static arc arcs_68_2[2] = { {154, 7}, {156, 4}, }; static arc arcs_68_3[2] = { {158, 8}, {159, 4}, }; static arc arcs_68_4[1] = { {0, 4}, }; static arc arcs_68_5[2] = { {161, 5}, {0, 5}, }; static arc arcs_68_6[1] = { {15, 4}, }; static arc arcs_68_7[1] = { {156, 4}, }; static arc arcs_68_8[1] = { {159, 4}, }; static state states_68[9] = { {.s_narcs=10, .s_arc=arcs_68_0}, {.s_narcs=3, .s_arc=arcs_68_1}, {.s_narcs=2, .s_arc=arcs_68_2}, {.s_narcs=2, .s_arc=arcs_68_3}, {.s_narcs=1, .s_arc=arcs_68_4}, {.s_narcs=2, .s_arc=arcs_68_5}, {.s_narcs=1, .s_arc=arcs_68_6}, {.s_narcs=1, .s_arc=arcs_68_7}, {.s_narcs=1, .s_arc=arcs_68_8}, }; static arc arcs_69_0[2] = { {26, 1}, {51, 1}, }; static arc arcs_69_1[3] = { {165, 2}, {32, 3}, {0, 1}, }; static arc arcs_69_2[1] = { {0, 2}, }; static arc arcs_69_3[3] = { {26, 4}, {51, 4}, {0, 3}, }; static arc arcs_69_4[2] = { {32, 3}, {0, 4}, }; static state states_69[5] = { {.s_narcs=2, .s_arc=arcs_69_0}, {.s_narcs=3, .s_arc=arcs_69_1}, {.s_narcs=1, .s_arc=arcs_69_2}, {.s_narcs=3, .s_arc=arcs_69_3}, {.s_narcs=2, .s_arc=arcs_69_4}, }; static arc arcs_70_0[3] = { {13, 1}, {155, 2}, {82, 3}, }; static arc arcs_70_1[2] = { {14, 4}, {15, 5}, }; static arc arcs_70_2[1] = { {166, 6}, }; static arc arcs_70_3[1] = { {23, 5}, }; static arc arcs_70_4[1] = { {15, 5}, }; static arc arcs_70_5[1] = { {0, 5}, }; static arc arcs_70_6[1] = { {156, 5}, }; static state states_70[7] = { {.s_narcs=3, .s_arc=arcs_70_0}, {.s_narcs=2, .s_arc=arcs_70_1}, {.s_narcs=1, .s_arc=arcs_70_2}, {.s_narcs=1, .s_arc=arcs_70_3}, {.s_narcs=1, .s_arc=arcs_70_4}, {.s_narcs=1, .s_arc=arcs_70_5}, {.s_narcs=1, .s_arc=arcs_70_6}, }; static arc arcs_71_0[1] = { {167, 1}, }; static arc arcs_71_1[2] = { {32, 2}, {0, 1}, }; static arc arcs_71_2[2] = { {167, 1}, {0, 2}, }; static state states_71[3] = { {.s_narcs=1, .s_arc=arcs_71_0}, {.s_narcs=2, .s_arc=arcs_71_1}, {.s_narcs=2, .s_arc=arcs_71_2}, }; static arc arcs_72_0[2] = { {26, 1}, {27, 2}, }; static arc arcs_72_1[2] = { {27, 2}, {0, 1}, }; static arc arcs_72_2[3] = { {26, 3}, {168, 4}, {0, 2}, }; static arc arcs_72_3[2] = { {168, 4}, {0, 3}, }; static arc arcs_72_4[1] = { {0, 4}, }; static state states_72[5] = { {.s_narcs=2, .s_arc=arcs_72_0}, {.s_narcs=2, .s_arc=arcs_72_1}, {.s_narcs=3, .s_arc=arcs_72_2}, {.s_narcs=2, .s_arc=arcs_72_3}, {.s_narcs=1, .s_arc=arcs_72_4}, }; static arc arcs_73_0[1] = { {27, 1}, }; static arc arcs_73_1[2] = { {26, 2}, {0, 1}, }; static arc arcs_73_2[1] = { {0, 2}, }; static state states_73[3] = { {.s_narcs=1, .s_arc=arcs_73_0}, {.s_narcs=2, .s_arc=arcs_73_1}, {.s_narcs=1, .s_arc=arcs_73_2}, }; static arc arcs_74_0[2] = { {108, 1}, {51, 1}, }; static arc arcs_74_1[2] = { {32, 2}, {0, 1}, }; static arc arcs_74_2[3] = { {108, 1}, {51, 1}, {0, 2}, }; static state states_74[3] = { {.s_narcs=2, .s_arc=arcs_74_0}, {.s_narcs=2, .s_arc=arcs_74_1}, {.s_narcs=3, .s_arc=arcs_74_2}, }; static arc arcs_75_0[1] = { {26, 1}, }; static arc arcs_75_1[2] = { {32, 2}, {0, 1}, }; static arc arcs_75_2[2] = { {26, 1}, {0, 2}, }; static state states_75[3] = { {.s_narcs=1, .s_arc=arcs_75_0}, {.s_narcs=2, .s_arc=arcs_75_1}, {.s_narcs=2, .s_arc=arcs_75_2}, }; static arc arcs_76_0[3] = { {26, 1}, {34, 2}, {51, 3}, }; static arc arcs_76_1[4] = { {27, 4}, {165, 5}, {32, 6}, {0, 1}, }; static arc arcs_76_2[1] = { {108, 7}, }; static arc arcs_76_3[3] = { {165, 5}, {32, 6}, {0, 3}, }; static arc arcs_76_4[1] = { {26, 7}, }; static arc arcs_76_5[1] = { {0, 5}, }; static arc arcs_76_6[3] = { {26, 8}, {51, 8}, {0, 6}, }; static arc arcs_76_7[3] = { {165, 5}, {32, 9}, {0, 7}, }; static arc arcs_76_8[2] = { {32, 6}, {0, 8}, }; static arc arcs_76_9[3] = { {26, 10}, {34, 11}, {0, 9}, }; static arc arcs_76_10[1] = { {27, 12}, }; static arc arcs_76_11[1] = { {108, 13}, }; static arc arcs_76_12[1] = { {26, 13}, }; static arc arcs_76_13[2] = { {32, 9}, {0, 13}, }; static state states_76[14] = { {.s_narcs=3, .s_arc=arcs_76_0}, {.s_narcs=4, .s_arc=arcs_76_1}, {.s_narcs=1, .s_arc=arcs_76_2}, {.s_narcs=3, .s_arc=arcs_76_3}, {.s_narcs=1, .s_arc=arcs_76_4}, {.s_narcs=1, .s_arc=arcs_76_5}, {.s_narcs=3, .s_arc=arcs_76_6}, {.s_narcs=3, .s_arc=arcs_76_7}, {.s_narcs=2, .s_arc=arcs_76_8}, {.s_narcs=3, .s_arc=arcs_76_9}, {.s_narcs=1, .s_arc=arcs_76_10}, {.s_narcs=1, .s_arc=arcs_76_11}, {.s_narcs=1, .s_arc=arcs_76_12}, {.s_narcs=2, .s_arc=arcs_76_13}, }; static arc arcs_77_0[1] = { {169, 1}, }; static arc arcs_77_1[1] = { {23, 2}, }; static arc arcs_77_2[2] = { {13, 3}, {27, 4}, }; static arc arcs_77_3[2] = { {14, 5}, {15, 6}, }; static arc arcs_77_4[1] = { {28, 7}, }; static arc arcs_77_5[1] = { {15, 6}, }; static arc arcs_77_6[1] = { {27, 4}, }; static arc arcs_77_7[1] = { {0, 7}, }; static state states_77[8] = { {.s_narcs=1, .s_arc=arcs_77_0}, {.s_narcs=1, .s_arc=arcs_77_1}, {.s_narcs=2, .s_arc=arcs_77_2}, {.s_narcs=2, .s_arc=arcs_77_3}, {.s_narcs=1, .s_arc=arcs_77_4}, {.s_narcs=1, .s_arc=arcs_77_5}, {.s_narcs=1, .s_arc=arcs_77_6}, {.s_narcs=1, .s_arc=arcs_77_7}, }; static arc arcs_78_0[1] = { {170, 1}, }; static arc arcs_78_1[2] = { {32, 2}, {0, 1}, }; static arc arcs_78_2[2] = { {170, 1}, {0, 2}, }; static state states_78[3] = { {.s_narcs=1, .s_arc=arcs_78_0}, {.s_narcs=2, .s_arc=arcs_78_1}, {.s_narcs=2, .s_arc=arcs_78_2}, }; static arc arcs_79_0[3] = { {26, 1}, {34, 2}, {33, 2}, }; static arc arcs_79_1[3] = { {165, 3}, {31, 2}, {0, 1}, }; static arc arcs_79_2[1] = { {26, 3}, }; static arc arcs_79_3[1] = { {0, 3}, }; static state states_79[4] = { {.s_narcs=3, .s_arc=arcs_79_0}, {.s_narcs=3, .s_arc=arcs_79_1}, {.s_narcs=1, .s_arc=arcs_79_2}, {.s_narcs=1, .s_arc=arcs_79_3}, }; static arc arcs_80_0[2] = { {165, 1}, {172, 1}, }; static arc arcs_80_1[1] = { {0, 1}, }; static state states_80[2] = { {.s_narcs=2, .s_arc=arcs_80_0}, {.s_narcs=1, .s_arc=arcs_80_1}, }; static arc arcs_81_0[2] = { {21, 1}, {101, 2}, }; static arc arcs_81_1[1] = { {101, 2}, }; static arc arcs_81_2[1] = { {66, 3}, }; static arc arcs_81_3[1] = { {102, 4}, }; static arc arcs_81_4[1] = { {112, 5}, }; static arc arcs_81_5[2] = { {171, 6}, {0, 5}, }; static arc arcs_81_6[1] = { {0, 6}, }; static state states_81[7] = { {.s_narcs=2, .s_arc=arcs_81_0}, {.s_narcs=1, .s_arc=arcs_81_1}, {.s_narcs=1, .s_arc=arcs_81_2}, {.s_narcs=1, .s_arc=arcs_81_3}, {.s_narcs=1, .s_arc=arcs_81_4}, {.s_narcs=2, .s_arc=arcs_81_5}, {.s_narcs=1, .s_arc=arcs_81_6}, }; static arc arcs_82_0[1] = { {97, 1}, }; static arc arcs_82_1[1] = { {114, 2}, }; static arc arcs_82_2[2] = { {171, 3}, {0, 2}, }; static arc arcs_82_3[1] = { {0, 3}, }; static state states_82[4] = { {.s_narcs=1, .s_arc=arcs_82_0}, {.s_narcs=1, .s_arc=arcs_82_1}, {.s_narcs=2, .s_arc=arcs_82_2}, {.s_narcs=1, .s_arc=arcs_82_3}, }; static arc arcs_83_0[1] = { {23, 1}, }; static arc arcs_83_1[1] = { {0, 1}, }; static state states_83[2] = { {.s_narcs=1, .s_arc=arcs_83_0}, {.s_narcs=1, .s_arc=arcs_83_1}, }; static arc arcs_84_0[1] = { {174, 1}, }; static arc arcs_84_1[2] = { {175, 2}, {0, 1}, }; static arc arcs_84_2[1] = { {0, 2}, }; static state states_84[3] = { {.s_narcs=1, .s_arc=arcs_84_0}, {.s_narcs=2, .s_arc=arcs_84_1}, {.s_narcs=1, .s_arc=arcs_84_2}, }; static arc arcs_85_0[2] = { {77, 1}, {9, 2}, }; static arc arcs_85_1[1] = { {26, 2}, }; static arc arcs_85_2[1] = { {0, 2}, }; static state states_85[3] = { {.s_narcs=2, .s_arc=arcs_85_0}, {.s_narcs=1, .s_arc=arcs_85_1}, {.s_narcs=1, .s_arc=arcs_85_2}, }; static dfa dfas[86] = { {256, "single_input", 0, 3, states_0, "\004\050\340\000\002\000\000\000\012\076\011\007\262\004\020\002\000\300\220\050\037\102"}, {257, "file_input", 0, 2, states_1, "\204\050\340\000\002\000\000\000\012\076\011\007\262\004\020\002\000\300\220\050\037\102"}, {258, "eval_input", 0, 3, states_2, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {259, "decorator", 0, 7, states_3, "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {260, "decorators", 0, 2, states_4, "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {261, "decorated", 0, 3, states_5, "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {262, "async_funcdef", 0, 3, states_6, "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {263, "funcdef", 0, 8, states_7, "\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {264, "parameters", 0, 4, states_8, "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {265, "typedargslist", 0, 19, states_9, "\000\000\200\000\006\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {266, "tfpdef", 0, 4, states_10, "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {267, "varargslist", 0, 19, states_11, "\000\000\200\000\006\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {268, "vfpdef", 0, 2, states_12, "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {269, "stmt", 0, 2, states_13, "\000\050\340\000\002\000\000\000\012\076\011\007\262\004\020\002\000\300\220\050\037\102"}, {270, "simple_stmt", 0, 4, states_14, "\000\040\200\000\002\000\000\000\012\076\011\007\000\000\020\002\000\300\220\050\037\100"}, {271, "small_stmt", 0, 2, states_15, "\000\040\200\000\002\000\000\000\012\076\011\007\000\000\020\002\000\300\220\050\037\100"}, {272, "expr_stmt", 0, 6, states_16, "\000\040\200\000\002\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {273, "annassign", 0, 5, states_17, "\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {274, "testlist_star_expr", 0, 3, states_18, "\000\040\200\000\002\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {275, "augassign", 0, 2, states_19, "\000\000\000\000\000\000\360\377\001\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {276, "del_stmt", 0, 3, states_20, "\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {277, "pass_stmt", 0, 2, states_21, "\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {278, "flow_stmt", 0, 2, states_22, "\000\000\000\000\000\000\000\000\000\036\000\000\000\000\000\000\000\000\000\000\000\100"}, {279, "break_stmt", 0, 2, states_23, "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000"}, {280, "continue_stmt", 0, 2, states_24, "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000"}, {281, "return_stmt", 0, 3, states_25, "\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000"}, {282, "yield_stmt", 0, 2, states_26, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\100"}, {283, "raise_stmt", 0, 5, states_27, "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, {284, "import_stmt", 0, 2, states_28, "\000\000\000\000\000\000\000\000\000\040\001\000\000\000\000\000\000\000\000\000\000\000"}, {285, "import_name", 0, 3, states_29, "\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000"}, {286, "import_from", 0, 8, states_30, "\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, {287, "import_as_name", 0, 4, states_31, "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {288, "dotted_as_name", 0, 4, states_32, "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {289, "import_as_names", 0, 3, states_33, "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {290, "dotted_as_names", 0, 2, states_34, "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {291, "dotted_name", 0, 2, states_35, "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {292, "global_stmt", 0, 3, states_36, "\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000"}, {293, "nonlocal_stmt", 0, 3, states_37, "\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000"}, {294, "assert_stmt", 0, 5, states_38, "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000"}, {295, "compound_stmt", 0, 2, states_39, "\000\010\140\000\000\000\000\000\000\000\000\000\262\004\000\000\000\000\000\000\000\002"}, {296, "async_stmt", 0, 3, states_40, "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {297, "if_stmt", 0, 8, states_41, "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, {298, "while_stmt", 0, 8, states_42, "\000\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000"}, {299, "for_stmt", 0, 10, states_43, "\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000"}, {300, "try_stmt", 0, 13, states_44, "\000\000\000\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000"}, {301, "with_stmt", 0, 5, states_45, "\000\000\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000"}, {302, "with_item", 0, 4, states_46, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {303, "except_clause", 0, 5, states_47, "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, {304, "suite", 0, 5, states_48, "\004\040\200\000\002\000\000\000\012\076\011\007\000\000\020\002\000\300\220\050\037\100"}, {305, "test", 0, 6, states_49, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {306, "test_nocond", 0, 2, states_50, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {307, "lambdef", 0, 5, states_51, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000"}, {308, "lambdef_nocond", 0, 5, states_52, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000"}, {309, "or_test", 0, 2, states_53, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\002\000\300\220\050\037\000"}, {310, "and_test", 0, 2, states_54, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\002\000\300\220\050\037\000"}, {311, "not_test", 0, 3, states_55, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\002\000\300\220\050\037\000"}, {312, "comparison", 0, 2, states_56, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\000\000\300\220\050\037\000"}, {313, "comp_op", 0, 4, states_57, "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\362\017\000\000\000\000\000"}, {314, "star_expr", 0, 3, states_58, "\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {315, "expr", 0, 2, states_59, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\000\000\300\220\050\037\000"}, {316, "xor_expr", 0, 2, states_60, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\000\000\300\220\050\037\000"}, {317, "and_expr", 0, 2, states_61, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\000\000\300\220\050\037\000"}, {318, "shift_expr", 0, 2, states_62, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\000\000\300\220\050\037\000"}, {319, "arith_expr", 0, 2, states_63, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\000\000\300\220\050\037\000"}, {320, "term", 0, 2, states_64, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\000\000\300\220\050\037\000"}, {321, "factor", 0, 3, states_65, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\000\000\300\220\050\037\000"}, {322, "power", 0, 4, states_66, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\200\050\037\000"}, {323, "atom_expr", 0, 3, states_67, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\200\050\037\000"}, {324, "atom", 0, 9, states_68, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\050\037\000"}, {325, "testlist_comp", 0, 5, states_69, "\000\040\200\000\002\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {326, "trailer", 0, 7, states_70, "\000\040\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\010\000\000"}, {327, "subscriptlist", 0, 3, states_71, "\000\040\200\010\000\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {328, "subscript", 0, 5, states_72, "\000\040\200\010\000\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {329, "sliceop", 0, 3, states_73, "\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {330, "exprlist", 0, 3, states_74, "\000\040\200\000\002\000\000\000\000\000\010\000\000\000\000\000\000\300\220\050\037\000"}, {331, "testlist", 0, 3, states_75, "\000\040\200\000\000\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {332, "dictorsetmaker", 0, 14, states_76, "\000\040\200\000\006\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {333, "classdef", 0, 8, states_77, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"}, {334, "arglist", 0, 3, states_78, "\000\040\200\000\006\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {335, "argument", 0, 4, states_79, "\000\040\200\000\006\000\000\000\000\000\010\000\000\000\020\002\000\300\220\050\037\000"}, {336, "comp_iter", 0, 2, states_80, "\000\000\040\000\000\000\000\000\000\000\000\000\042\000\000\000\000\000\000\000\000\000"}, {337, "comp_for", 0, 7, states_81, "\000\000\040\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000"}, {338, "comp_if", 0, 4, states_82, "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"}, {339, "encoding_decl", 0, 2, states_83, "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {340, "yield_expr", 0, 3, states_84, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\100"}, {341, "yield_arg", 0, 3, states_85, "\000\040\200\000\000\000\000\000\000\040\010\000\000\000\020\002\000\300\220\050\037\000"}, }; label labels[176] = { {0, "EMPTY"}, {256, 0}, {4, 0}, {270, 0}, {295, 0}, {257, 0}, {269, 0}, {0, 0}, {258, 0}, {331, 0}, {259, 0}, {49, 0}, {291, 0}, {7, 0}, {334, 0}, {8, 0}, {260, 0}, {261, 0}, {333, 0}, {263, 0}, {262, 0}, {55, 0}, {1, "def"}, {1, 0}, {264, 0}, {51, 0}, {305, 0}, {11, 0}, {304, 0}, {265, 0}, {266, 0}, {22, 0}, {12, 0}, {16, 0}, {35, 0}, {267, 0}, {268, 0}, {271, 0}, {13, 0}, {272, 0}, {276, 0}, {277, 0}, {278, 0}, {284, 0}, {292, 0}, {293, 0}, {294, 0}, {274, 0}, {273, 0}, {275, 0}, {340, 0}, {314, 0}, {36, 0}, {37, 0}, {38, 0}, {50, 0}, {39, 0}, {40, 0}, {41, 0}, {42, 0}, {43, 0}, {44, 0}, {45, 0}, {46, 0}, {48, 0}, {1, "del"}, {330, 0}, {1, "pass"}, {279, 0}, {280, 0}, {281, 0}, {283, 0}, {282, 0}, {1, "break"}, {1, "continue"}, {1, "return"}, {1, "raise"}, {1, "from"}, {285, 0}, {286, 0}, {1, "import"}, {290, 0}, {23, 0}, {52, 0}, {289, 0}, {287, 0}, {1, "as"}, {288, 0}, {1, "global"}, {1, "nonlocal"}, {1, "assert"}, {297, 0}, {298, 0}, {299, 0}, {300, 0}, {301, 0}, {296, 0}, {1, "if"}, {1, "elif"}, {1, "else"}, {1, "while"}, {1, "for"}, {1, "in"}, {1, "try"}, {303, 0}, {1, "finally"}, {1, "with"}, {302, 0}, {315, 0}, {1, "except"}, {5, 0}, {6, 0}, {309, 0}, {307, 0}, {306, 0}, {308, 0}, {1, "lambda"}, {310, 0}, {1, "or"}, {311, 0}, {1, "and"}, {1, "not"}, {312, 0}, {313, 0}, {20, 0}, {21, 0}, {27, 0}, {30, 0}, {29, 0}, {28, 0}, {28, 0}, {1, "is"}, {316, 0}, {18, 0}, {317, 0}, {32, 0}, {318, 0}, {19, 0}, {319, 0}, {33, 0}, {34, 0}, {320, 0}, {14, 0}, {15, 0}, {321, 0}, {17, 0}, {24, 0}, {47, 0}, {31, 0}, {322, 0}, {323, 0}, {54, 0}, {324, 0}, {326, 0}, {325, 0}, {9, 0}, {10, 0}, {25, 0}, {332, 0}, {26, 0}, {2, 0}, {3, 0}, {1, "None"}, {1, "True"}, {1, "False"}, {337, 0}, {327, 0}, {328, 0}, {329, 0}, {1, "class"}, {335, 0}, {336, 0}, {338, 0}, {339, 0}, {1, "yield"}, {341, 0}, }; grammar _PyParser_Grammar = { 86, dfas, {176, labels}, 256 };
51,109
2,271
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/errors.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/errno.h" #include "libc/mem/mem.h" #include "libc/nt/enum/formatmessageflags.h" #include "libc/nt/enum/lang.h" #include "libc/nt/memory.h" #include "libc/nt/process.h" #include "libc/nt/runtime.h" #include "libc/x/x.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/fileutils.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/traceback.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/unicodeobject.h" /* clang-format off */ _Py_IDENTIFIER(builtins); _Py_IDENTIFIER(stderr); void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback) { PyThreadState *tstate = PyThreadState_GET(); PyObject *oldtype, *oldvalue, *oldtraceback; if (traceback != NULL && !PyTraceBack_Check(traceback)) { /* XXX Should never happen -- fatal error instead? */ /* Well, it could be None. */ Py_DECREF(traceback); traceback = NULL; } /* Save these in locals to safeguard against recursive invocation through Py_XDECREF */ oldtype = tstate->curexc_type; oldvalue = tstate->curexc_value; oldtraceback = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = traceback; Py_XDECREF(oldtype); Py_XDECREF(oldvalue); Py_XDECREF(oldtraceback); } static PyObject* _PyErr_CreateException(PyObject *exception, PyObject *value) { if (value == NULL || value == Py_None) { return _PyObject_CallNoArg(exception); } else if (PyTuple_Check(value)) { return PyObject_Call(exception, value, NULL); } else { return _PyObject_CallArg1(exception, value); } } void PyErr_SetObject(PyObject *exception, PyObject *value) { PyThreadState *tstate = PyThreadState_GET(); PyObject *exc_value; PyObject *tb = NULL; if (exception != NULL && !PyExceptionClass_Check(exception)) { PyErr_Format(PyExc_SystemError, "exception %R not a BaseException subclass", exception); return; } Py_XINCREF(value); exc_value = tstate->exc_value; if (exc_value != NULL && exc_value != Py_None) { /* Implicit exception chaining */ Py_INCREF(exc_value); if (value == NULL || !PyExceptionInstance_Check(value)) { /* We must normalize the value right now */ PyObject *fixed_value; /* Issue #23571: functions must not be called with an exception set */ PyErr_Clear(); fixed_value = _PyErr_CreateException(exception, value); Py_XDECREF(value); if (fixed_value == NULL) { Py_DECREF(exc_value); return; } value = fixed_value; } /* Avoid reference cycles through the context chain. This is O(chain length) but context chains are usually very short. Sensitive readers may try to inline the call to PyException_GetContext. */ if (exc_value != value) { PyObject *o = exc_value, *context; while ((context = PyException_GetContext(o))) { Py_DECREF(context); if (context == value) { PyException_SetContext(o, NULL); break; } o = context; } PyException_SetContext(value, exc_value); } else { Py_DECREF(exc_value); } } if (value != NULL && PyExceptionInstance_Check(value)) tb = PyException_GetTraceback(value); Py_XINCREF(exception); PyErr_Restore(exception, value, tb); } /* Set a key error with the specified argument, wrapping it in a * tuple automatically so that tuple keys are not unpacked as the * exception arguments. */ void _PyErr_SetKeyError(PyObject *arg) { PyObject *tup; tup = PyTuple_Pack(1, arg); if (!tup) return; /* caller will expect error to be set anyway */ PyErr_SetObject(PyExc_KeyError, tup); Py_DECREF(tup); } void PyErr_SetNone(PyObject *exception) { PyErr_SetObject(exception, (PyObject *)NULL); } void PyErr_SetString(PyObject *exception, const char *string) { PyObject *value = PyUnicode_FromString(string); PyErr_SetObject(exception, value); Py_XDECREF(value); } PyObject * _Py_HOT_FUNCTION PyErr_Occurred(void) { PyThreadState *tstate = _PyThreadState_UncheckedGet(); return tstate == NULL ? NULL : tstate->curexc_type; } int PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc) { if (err == NULL || exc == NULL) { /* maybe caused by "import exceptions" that failed early on */ return 0; } if (PyTuple_Check(exc)) { Py_ssize_t i, n; n = PyTuple_Size(exc); for (i = 0; i < n; i++) { /* Test recursively */ if (PyErr_GivenExceptionMatches( err, PyTuple_GET_ITEM(exc, i))) { return 1; } } return 0; } /* err might be an instance, so check its class. */ if (PyExceptionInstance_Check(err)) err = PyExceptionInstance_Class(err); if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) { int res = 0; PyObject *exception, *value, *tb; PyErr_Fetch(&exception, &value, &tb); /* PyObject_IsSubclass() can recurse and therefore is not safe (see test_bad_getattr in test.pickletester). */ res = PyType_IsSubtype((PyTypeObject *)err, (PyTypeObject *)exc); /* This function must not fail, so print the error here */ if (res == -1) { PyErr_WriteUnraisable(err); res = 0; } PyErr_Restore(exception, value, tb); return res; } return err == exc; } int PyErr_ExceptionMatches(PyObject *exc) { return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc); } #ifndef Py_NORMALIZE_RECURSION_LIMIT #define Py_NORMALIZE_RECURSION_LIMIT 32 #endif /* Used in many places to normalize a raised exception, including in eval_code2(), do_raise(), and PyErr_Print() XXX: should PyErr_NormalizeException() also call PyException_SetTraceback() with the resulting value and tb? */ static void PyErr_NormalizeExceptionEx(PyObject **exc, PyObject **val, PyObject **tb, int recursion_depth) { PyObject *type = *exc; PyObject *value = *val; PyObject *inclass = NULL; PyObject *initial_tb = NULL; if (type == NULL) { /* There was no exception, so nothing to do. */ return; } /* If PyErr_SetNone() was used, the value will have been actually set to NULL. */ if (!value) { value = Py_None; Py_INCREF(value); } if (PyExceptionInstance_Check(value)) inclass = PyExceptionInstance_Class(value); /* Normalize the exception so that if the type is a class, the value will be an instance. */ if (PyExceptionClass_Check(type)) { int is_subclass; if (inclass) { is_subclass = PyObject_IsSubclass(inclass, type); if (is_subclass < 0) goto finally; } else is_subclass = 0; /* if the value was not an instance, or is not an instance whose class is (or is derived from) type, then use the value as an argument to instantiation of the type class. */ if (!inclass || !is_subclass) { PyObject *fixed_value; fixed_value = _PyErr_CreateException(type, value); if (fixed_value == NULL) { goto finally; } Py_DECREF(value); value = fixed_value; } /* if the class of the instance doesn't exactly match the class of the type, believe the instance */ else if (inclass != type) { Py_DECREF(type); type = inclass; Py_INCREF(type); } } *exc = type; *val = value; return; finally: Py_DECREF(type); Py_DECREF(value); if (recursion_depth + 1 == Py_NORMALIZE_RECURSION_LIMIT) { PyErr_SetString(PyExc_RecursionError, "maximum recursion depth " "exceeded while normalizing an exception"); } /* If the new exception doesn't set a traceback and the old exception had a traceback, use the old traceback for the new exception. It's better than nothing. */ initial_tb = *tb; PyErr_Fetch(exc, val, tb); if (initial_tb != NULL) { if (*tb == NULL) *tb = initial_tb; else Py_DECREF(initial_tb); } /* Normalize recursively. * Abort when Py_NORMALIZE_RECURSION_LIMIT has been exceeded and the * corresponding RecursionError could not be normalized.*/ if (++recursion_depth > Py_NORMALIZE_RECURSION_LIMIT) { if (PyErr_GivenExceptionMatches(*exc, PyExc_MemoryError)) { Py_FatalError("Cannot recover from MemoryErrors " "while normalizing exceptions."); } else { Py_FatalError("Cannot recover from the recursive normalization " "of an exception."); } } PyErr_NormalizeExceptionEx(exc, val, tb, recursion_depth); } void PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb) { PyErr_NormalizeExceptionEx(exc, val, tb, 0); } void PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback) { PyThreadState *tstate = PyThreadState_GET(); *p_type = tstate->curexc_type; *p_value = tstate->curexc_value; *p_traceback = tstate->curexc_traceback; tstate->curexc_type = NULL; tstate->curexc_value = NULL; tstate->curexc_traceback = NULL; } void PyErr_Clear(void) { PyErr_Restore(NULL, NULL, NULL); } void PyErr_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback) { PyThreadState *tstate = PyThreadState_GET(); *p_type = tstate->exc_type; *p_value = tstate->exc_value; *p_traceback = tstate->exc_traceback; Py_XINCREF(*p_type); Py_XINCREF(*p_value); Py_XINCREF(*p_traceback); } void PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback) { PyObject *oldtype, *oldvalue, *oldtraceback; PyThreadState *tstate = PyThreadState_GET(); oldtype = tstate->exc_type; oldvalue = tstate->exc_value; oldtraceback = tstate->exc_traceback; tstate->exc_type = p_type; tstate->exc_value = p_value; tstate->exc_traceback = p_traceback; Py_XDECREF(oldtype); Py_XDECREF(oldvalue); Py_XDECREF(oldtraceback); } /* Like PyErr_Restore(), but if an exception is already set, set the context associated with it. */ void _PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb) { if (exc == NULL) return; if (PyErr_Occurred()) { PyObject *exc2, *val2, *tb2; PyErr_Fetch(&exc2, &val2, &tb2); PyErr_NormalizeException(&exc, &val, &tb); if (tb != NULL) { PyException_SetTraceback(val, tb); Py_DECREF(tb); } Py_DECREF(exc); PyErr_NormalizeException(&exc2, &val2, &tb2); PyException_SetContext(val2, val); PyErr_Restore(exc2, val2, tb2); } else { PyErr_Restore(exc, val, tb); } } static PyObject * _PyErr_FormatVFromCause(PyObject *exception, const char *format, va_list vargs) { PyObject *exc, *val, *val2, *tb; assert(PyErr_Occurred()); PyErr_Fetch(&exc, &val, &tb); PyErr_NormalizeException(&exc, &val, &tb); if (tb != NULL) { PyException_SetTraceback(val, tb); Py_DECREF(tb); } Py_DECREF(exc); assert(!PyErr_Occurred()); PyErr_FormatV(exception, format, vargs); PyErr_Fetch(&exc, &val2, &tb); PyErr_NormalizeException(&exc, &val2, &tb); Py_INCREF(val); PyException_SetCause(val2, val); PyException_SetContext(val2, val); PyErr_Restore(exc, val2, tb); return NULL; } PyObject * _PyErr_FormatFromCause(PyObject *exception, const char *format, ...) { va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, format); #else va_start(vargs); #endif _PyErr_FormatVFromCause(exception, format, vargs); va_end(vargs); return NULL; } /* Convenience functions to set a type error exception and return 0 */ int PyErr_BadArgument(void) { PyErr_SetString(PyExc_TypeError, "bad argument type for built-in operation"); return 0; } PyObject * PyErr_NoMemory(void) { if (Py_TYPE(PyExc_MemoryError) == NULL) { /* PyErr_NoMemory() has been called before PyExc_MemoryError has been initialized by _PyExc_Init() */ Py_FatalError("Out of memory and PyExc_MemoryError is not " "initialized yet"); } PyErr_SetNone(PyExc_MemoryError); return NULL; } PyObject * PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject) { return PyErr_SetFromErrnoWithFilenameObjects(exc, filenameObject, NULL); } PyObject * PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2) { PyObject *message; PyObject *v, *args; int i = errno; #ifdef MS_WINDOWS WCHAR *s_buf = NULL; #endif /* Unix/Windows */ #ifdef EINTR if (i == EINTR && PyErr_CheckSignals()) return NULL; #endif #ifndef MS_WINDOWS if (i != 0) { char *s = strerror(i); message = PyUnicode_DecodeLocale(s, "surrogateescape"); } else { /* Sometimes errno didn't get set */ message = PyUnicode_FromString("Error"); } #else if (i == 0) message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */ else { /* Note that the Win32 errors do not lineup with the errno error. So if the error is in the MSVC error table, we use it, otherwise we assume it really _is_ a Win32 error code */ if (i > 0 && i < _sys_nerr) { message = PyUnicode_FromString(_sys_errlist[i]); } else { int len = FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, /* no message source */ i, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ (LPWSTR) &s_buf, 0, /* size not used */ NULL); /* no args */ if (len==0) { /* Only ever seen this in out-of-mem situations */ s_buf = NULL; message = PyUnicode_FromFormat("Windows Error 0x%x", i); } else { /* remove trailing cr/lf and dots */ while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) s_buf[--len] = L'\0'; message = PyUnicode_FromWideChar(s_buf, len); } } } #endif /* Unix/Windows */ if (message == NULL) { #ifdef MS_WINDOWS LocalFree(s_buf); #endif return NULL; } if (filenameObject != NULL) { if (filenameObject2 != NULL) args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2); else args = Py_BuildValue("(iOO)", i, message, filenameObject); } else { assert(filenameObject2 == NULL); args = Py_BuildValue("(iO)", i, message); } Py_DECREF(message); if (args != NULL) { v = PyObject_Call(exc, args, NULL); Py_DECREF(args); if (v != NULL) { PyErr_SetObject((PyObject *) Py_TYPE(v), v); Py_DECREF(v); } } #ifdef MS_WINDOWS LocalFree(s_buf); #endif return NULL; } PyObject * PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename) { PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL; PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL); Py_XDECREF(name); return result; } PyObject * PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename) { PyObject *name = filename ? PyUnicode_FromUnicode(filename, wcslen(filename)) : NULL; PyObject *result = PyErr_SetFromErrnoWithFilenameObjects(exc, name, NULL); Py_XDECREF(name); return result; } PyObject * PyErr_SetFromErrno(PyObject *exc) { return PyErr_SetFromErrnoWithFilenameObjects(exc, NULL, NULL); } PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects( PyObject *exc, int ierr, PyObject *filenameObject, PyObject *filenameObject2) { int len; size_t buf32z; wchar_t *buf32; char16_t *s_buf = NULL; /* Free via LocalFree */ PyObject *message; PyObject *args, *v; uint32_t err = (uint32_t)ierr; if (err==0) err = GetLastError(); len = FormatMessage( /* Error API error */ kNtFormatMessageAllocateBuffer | kNtFormatMessageFromSystem | kNtFormatMessageIgnoreInserts, NULL, /* no message source */ err, MAKELANGID(kNtLangNeutral, kNtSublangDefault), (char16_t *)&s_buf, 0, /* size not used */ NULL); /* no args */ if (len==0) { /* Only seen this in out of mem situations */ message = PyUnicode_FromFormat("Windows Error 0x%x", err); s_buf = NULL; } else { /* remove trailing cr/lf and dots */ while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) s_buf[--len] = L'\0'; buf32 = utf16to32(s_buf, len, &buf32z); message = PyUnicode_FromWideChar(buf32, buf32z); free(buf32); } if (message == NULL) { LocalFree(s_buf); return NULL; } if (filenameObject == NULL) { assert(filenameObject2 == NULL); filenameObject = filenameObject2 = Py_None; } else if (filenameObject2 == NULL) filenameObject2 = Py_None; /* This is the constructor signature for OSError. The POSIX translation will be figured out by the constructor. */ args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2); Py_DECREF(message); if (args != NULL) { v = PyObject_Call(exc, args, NULL); Py_DECREF(args); if (v != NULL) { PyErr_SetObject((PyObject *) Py_TYPE(v), v); Py_DECREF(v); } } LocalFree(s_buf); return NULL; } /* Windows specific error code handling */ PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject( PyObject *exc, int ierr, PyObject *filenameObject) { return PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr, filenameObject, NULL); } PyObject *PyErr_SetExcFromWindowsErrWithFilename( PyObject *exc, int ierr, const char *filename) { PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL; PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr, name, NULL); Py_XDECREF(name); return ret; } PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename( PyObject *exc, int ierr, const Py_UNICODE *filename) { PyObject *name = filename ? PyUnicode_FromUnicode(filename, wcslen(filename)) : NULL; PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObjects(exc, ierr, name, NULL); Py_XDECREF(name); return ret; } PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr) { return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL); } PyObject *PyErr_SetFromWindowsErr(int ierr) { return PyErr_SetExcFromWindowsErrWithFilename(PyExc_OSError, ierr, NULL); } PyObject *PyErr_SetFromWindowsErrWithFilename( int ierr, const char *filename) { PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL; PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects( PyExc_OSError, ierr, name, NULL); Py_XDECREF(name); return result; } PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename( int ierr, const Py_UNICODE *filename) { PyObject *name = filename ? PyUnicode_FromUnicode(filename, wcslen(filename)) : NULL; PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObjects( PyExc_OSError, ierr, name, NULL); Py_XDECREF(name); return result; } PyObject * PyErr_SetImportErrorSubclass(PyObject *exception, PyObject *msg, PyObject *name, PyObject *path) { int issubclass; PyObject *kwargs, *error; issubclass = PyObject_IsSubclass(exception, PyExc_ImportError); if (issubclass < 0) { return NULL; } else if (!issubclass) { PyErr_SetString(PyExc_TypeError, "expected a subclass of ImportError"); return NULL; } if (msg == NULL) { PyErr_SetString(PyExc_TypeError, "expected a message argument"); return NULL; } if (name == NULL) { name = Py_None; } if (path == NULL) { path = Py_None; } kwargs = PyDict_New(); if (kwargs == NULL) { return NULL; } if (PyDict_SetItemString(kwargs, "name", name) < 0) { goto done; } if (PyDict_SetItemString(kwargs, "path", path) < 0) { goto done; } error = _PyObject_FastCallDict(exception, &msg, 1, kwargs); if (error != NULL) { PyErr_SetObject((PyObject *)Py_TYPE(error), error); Py_DECREF(error); } done: Py_DECREF(kwargs); return NULL; } PyObject * PyErr_SetImportError(PyObject *msg, PyObject *name, PyObject *path) { return PyErr_SetImportErrorSubclass(PyExc_ImportError, msg, name, path); } void _PyErr_BadInternalCall(const char *filename, int lineno) { PyErr_Format(PyExc_SystemError, "%s:%d: bad argument to internal function", filename, lineno); } /* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can export the entry point for existing object code: */ #undef PyErr_BadInternalCall void PyErr_BadInternalCall(void) { assert(0 && "bad argument to internal function"); PyErr_Format(PyExc_SystemError, "bad argument to internal function"); } #define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__) PyObject * PyErr_FormatV(PyObject *exception, const char *format, va_list vargs) { PyObject* string; /* Issue #23571: PyUnicode_FromFormatV() must not be called with an exception set, it calls arbitrary Python code like PyObject_Repr() */ PyErr_Clear(); string = PyUnicode_FromFormatV(format, vargs); PyErr_SetObject(exception, string); Py_XDECREF(string); return NULL; } PyObject * PyErr_Format(PyObject *exception, const char *format, ...) { va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, format); #else va_start(vargs); #endif PyErr_FormatV(exception, format, vargs); va_end(vargs); return NULL; } PyObject * PyErr_NewException(const char *name, PyObject *base, PyObject *dict) { const char *dot; PyObject *modulename = NULL; PyObject *classname = NULL; PyObject *mydict = NULL; PyObject *bases = NULL; PyObject *result = NULL; dot = strrchr(name, '.'); if (dot == NULL) { PyErr_SetString(PyExc_SystemError, "PyErr_NewException: name must be module.class"); return NULL; } if (base == NULL) base = PyExc_Exception; if (dict == NULL) { dict = mydict = PyDict_New(); if (dict == NULL) goto failure; } if (PyDict_GetItemString(dict, "__module__") == NULL) { modulename = PyUnicode_FromStringAndSize(name, (Py_ssize_t)(dot-name)); if (modulename == NULL) goto failure; if (PyDict_SetItemString(dict, "__module__", modulename) != 0) goto failure; } if (PyTuple_Check(base)) { bases = base; /* INCREF as we create a new ref in the else branch */ Py_INCREF(bases); } else { bases = PyTuple_Pack(1, base); if (bases == NULL) goto failure; } /* Create a real class. */ result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO", dot+1, bases, dict); failure: Py_XDECREF(bases); Py_XDECREF(mydict); Py_XDECREF(classname); Py_XDECREF(modulename); return result; } /* Create an exception with docstring */ PyObject * PyErr_NewExceptionWithDoc(const char *name, const char *doc, PyObject *base, PyObject *dict) { int result; PyObject *ret = NULL; PyObject *mydict = NULL; /* points to the dict only if we create it */ PyObject *docobj; if (dict == NULL) { dict = mydict = PyDict_New(); if (dict == NULL) { return NULL; } } if (doc != NULL) { docobj = PyUnicode_FromString(doc); if (docobj == NULL) goto failure; result = PyDict_SetItemString(dict, "__doc__", docobj); Py_DECREF(docobj); if (result < 0) goto failure; } ret = PyErr_NewException(name, base, dict); failure: Py_XDECREF(mydict); return ret; } /* Call when an exception has occurred but there is no way for Python to handle it. Examples: exception in __del__ or during GC. */ void PyErr_WriteUnraisable(PyObject *obj) { _Py_IDENTIFIER(__module__); PyObject *f, *t, *v, *tb; PyObject *moduleName = NULL; char* className; PyErr_Fetch(&t, &v, &tb); f = _PySys_GetObjectId(&PyId_stderr); if (f == NULL || f == Py_None) goto done; if (obj) { if (PyFile_WriteString("Exception ignored in: ", f) < 0) goto done; if (PyFile_WriteObject(obj, f, 0) < 0) { PyErr_Clear(); if (PyFile_WriteString("<object repr() failed>", f) < 0) { goto done; } } if (PyFile_WriteString("\n", f) < 0) goto done; } if (PyTraceBack_Print(tb, f) < 0) goto done; if (!t) goto done; assert(PyExceptionClass_Check(t)); className = PyExceptionClass_Name(t); if (className != NULL) { char *dot = strrchr(className, '.'); if (dot != NULL) className = dot+1; } moduleName = _PyObject_GetAttrId(t, &PyId___module__); if (moduleName == NULL || !PyUnicode_Check(moduleName)) { PyErr_Clear(); if (PyFile_WriteString("<unknown>", f) < 0) goto done; } else { if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) { if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0) goto done; if (PyFile_WriteString(".", f) < 0) goto done; } } if (className == NULL) { if (PyFile_WriteString("<unknown>", f) < 0) goto done; } else { if (PyFile_WriteString(className, f) < 0) goto done; } if (v && v != Py_None) { if (PyFile_WriteString(": ", f) < 0) goto done; if (PyFile_WriteObject(v, f, Py_PRINT_RAW) < 0) { PyErr_Clear(); if (PyFile_WriteString("<exception str() failed>", f) < 0) { goto done; } } } if (PyFile_WriteString("\n", f) < 0) goto done; done: Py_XDECREF(moduleName); Py_XDECREF(t); Py_XDECREF(v); Py_XDECREF(tb); PyErr_Clear(); /* Just in case */ } void PyErr_SyntaxLocation(const char *filename, int lineno) { PyErr_SyntaxLocationEx(filename, lineno, -1); } /* Set file and line information for the current exception. If the exception is not a SyntaxError, also sets additional attributes to make printing of exceptions believe it is a syntax error. */ void PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset) { PyObject *exc, *v, *tb, *tmp; _Py_IDENTIFIER(filename); _Py_IDENTIFIER(lineno); _Py_IDENTIFIER(msg); _Py_IDENTIFIER(offset); _Py_IDENTIFIER(print_file_and_line); _Py_IDENTIFIER(text); /* add attributes for the line number and filename for the error */ PyErr_Fetch(&exc, &v, &tb); PyErr_NormalizeException(&exc, &v, &tb); /* XXX check that it is, indeed, a syntax error. It might not * be, though. */ tmp = PyLong_FromLong(lineno); if (tmp == NULL) PyErr_Clear(); else { if (_PyObject_SetAttrId(v, &PyId_lineno, tmp)) PyErr_Clear(); Py_DECREF(tmp); } tmp = NULL; if (col_offset >= 0) { tmp = PyLong_FromLong(col_offset); if (tmp == NULL) PyErr_Clear(); } if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None)) PyErr_Clear(); Py_XDECREF(tmp); if (filename != NULL) { if (_PyObject_SetAttrId(v, &PyId_filename, filename)) PyErr_Clear(); tmp = PyErr_ProgramTextObject(filename, lineno); if (tmp) { if (_PyObject_SetAttrId(v, &PyId_text, tmp)) PyErr_Clear(); Py_DECREF(tmp); } } if (exc != PyExc_SyntaxError) { if (!_PyObject_HasAttrId(v, &PyId_msg)) { tmp = PyObject_Str(v); if (tmp) { if (_PyObject_SetAttrId(v, &PyId_msg, tmp)) PyErr_Clear(); Py_DECREF(tmp); } else { PyErr_Clear(); } } if (!_PyObject_HasAttrId(v, &PyId_print_file_and_line)) { if (_PyObject_SetAttrId(v, &PyId_print_file_and_line, Py_None)) PyErr_Clear(); } } PyErr_Restore(exc, v, tb); } void PyErr_SyntaxLocationEx(const char *filename, int lineno, int col_offset) { PyObject *fileobj; if (filename != NULL) { fileobj = PyUnicode_DecodeFSDefault(filename); if (fileobj == NULL) PyErr_Clear(); } else fileobj = NULL; PyErr_SyntaxLocationObject(fileobj, lineno, col_offset); Py_XDECREF(fileobj); } /* Attempt to load the line of text that the exception refers to. If it fails, it will return NULL but will not set an exception. XXX The functionality of this function is quite similar to the functionality in tb_displayline() in traceback.c. */ static PyObject * err_programtext(FILE *fp, int lineno) { int i; char linebuf[1000]; if (fp == NULL) return NULL; for (i = 0; i < lineno; i++) { char *pLastChar = &linebuf[sizeof(linebuf) - 2]; do { *pLastChar = '\0'; if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL) break; /* fgets read *something*; if it didn't get as far as pLastChar, it must have found a newline or hit the end of the file; if pLastChar is \n, it obviously found a newline; else we haven't yet seen a newline, so must continue */ } while (*pLastChar != '\0' && *pLastChar != '\n'); } fclose(fp); if (i == lineno) { PyObject *res; res = PyUnicode_FromString(linebuf); if (res == NULL) PyErr_Clear(); return res; } return NULL; } PyObject * PyErr_ProgramText(const char *filename, int lineno) { FILE *fp; if (filename == NULL || *filename == '\0' || lineno <= 0) return NULL; fp = _Py_fopen(filename, "r" PY_STDIOTEXTMODE); return err_programtext(fp, lineno); } PyObject * PyErr_ProgramTextObject(PyObject *filename, int lineno) { FILE *fp; if (filename == NULL || lineno <= 0) return NULL; fp = _Py_fopen_obj(filename, "r" PY_STDIOTEXTMODE); if (fp == NULL) { PyErr_Clear(); return NULL; } return err_programtext(fp, lineno); }
34,329
1,152
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/pystrtod.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/assert.h" #include "libc/errno.h" #include "libc/fmt/fmt.h" #include "libc/str/locale.h" #include "third_party/python/Include/dtoa.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pyfpe.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pyport.h" #include "third_party/python/Include/pystrtod.h" /* clang-format off */ /* Case-insensitive string match used for nan and inf detection; t should be lower-case. Returns 1 for a successful match, 0 otherwise. */ static int case_insensitive_match(const char *s, const char *t) { while(*t && Py_TOLOWER(*s) == *t) { s++; t++; } return *t ? 0 : 1; } /* _Py_parse_inf_or_nan: Attempt to parse a string of the form "nan", "inf" or "infinity", with an optional leading sign of "+" or "-". On success, return the NaN or Infinity as a double and set *endptr to point just beyond the successfully parsed portion of the string. On failure, return -1.0 and set *endptr to point to the start of the string. */ #ifndef PY_NO_SHORT_FLOAT_REPR double _Py_parse_inf_or_nan(const char *p, char **endptr) { double retval; const char *s; int negate = 0; s = p; if (*s == '-') { negate = 1; s++; } else if (*s == '+') { s++; } if (case_insensitive_match(s, "inf")) { s += 3; if (case_insensitive_match(s, "inity")) s += 5; retval = _Py_dg_infinity(negate); } else if (case_insensitive_match(s, "nan")) { s += 3; retval = _Py_dg_stdnan(negate); } else { s = p; retval = -1.0; } *endptr = (char *)s; return retval; } #else double _Py_parse_inf_or_nan(const char *p, char **endptr) { double retval; const char *s; int negate = 0; s = p; if (*s == '-') { negate = 1; s++; } else if (*s == '+') { s++; } if (case_insensitive_match(s, "inf")) { s += 3; if (case_insensitive_match(s, "inity")) s += 5; retval = negate ? -Py_HUGE_VAL : Py_HUGE_VAL; } #ifdef Py_NAN else if (case_insensitive_match(s, "nan")) { s += 3; retval = negate ? -Py_NAN : Py_NAN; } #endif else { s = p; retval = -1.0; } *endptr = (char *)s; return retval; } #endif /** * _PyOS_ascii_strtod: * @nptr: the string to convert to a numeric value. * @endptr: if non-%NULL, it returns the character after * the last character used in the conversion. * * Converts a string to a #gdouble value. * This function behaves like the standard strtod() function * does in the C locale. It does this without actually * changing the current locale, since that would not be * thread-safe. * * This function is typically used when reading configuration * files or other non-user input that should be locale independent. * To handle input from the user you should normally use the * locale-sensitive system strtod() function. * * If the correct value would cause overflow, plus or minus %HUGE_VAL * is returned (according to the sign of the value), and %ERANGE is * stored in %errno. If the correct value would cause underflow, * zero is returned and %ERANGE is stored in %errno. * If memory allocation fails, %ENOMEM is stored in %errno. * * This function resets %errno before calling strtod() so that * you can reliably detect overflow and underflow. * * Return value: the #gdouble value. **/ #ifndef PY_NO_SHORT_FLOAT_REPR static double _PyOS_ascii_strtod(const char *nptr, char **endptr) { double result; _Py_SET_53BIT_PRECISION_HEADER; assert(nptr != NULL); /* Set errno to zero, so that we can distinguish zero results and underflows */ errno = 0; _Py_SET_53BIT_PRECISION_START; result = _Py_dg_strtod(nptr, endptr); _Py_SET_53BIT_PRECISION_END; if (*endptr == nptr) /* string might represent an inf or nan */ result = _Py_parse_inf_or_nan(nptr, endptr); return result; } #else /* Use system strtod; since strtod is locale aware, we may have to first fix the decimal separator. Note that unlike _Py_dg_strtod, the system strtod may not always give correctly rounded results. */ static double _PyOS_ascii_strtod(const char *nptr, char **endptr) { char *fail_pos; double val; struct lconv *locale_data; const char *decimal_point; size_t decimal_point_len; const char *p, *decimal_point_pos; const char *end = NULL; /* Silence gcc */ const char *digits_pos = NULL; int negate = 0; assert(nptr != NULL); fail_pos = NULL; locale_data = localeconv(); decimal_point = locale_data->decimal_point; decimal_point_len = strlen(decimal_point); assert(decimal_point_len != 0); decimal_point_pos = NULL; /* Parse infinities and nans */ val = _Py_parse_inf_or_nan(nptr, endptr); if (*endptr != nptr) return val; /* Set errno to zero, so that we can distinguish zero results and underflows */ errno = 0; /* We process the optional sign manually, then pass the remainder to the system strtod. This ensures that the result of an underflow has the correct sign. (bug #1725) */ p = nptr; /* Process leading sign, if present */ if (*p == '-') { negate = 1; p++; } else if (*p == '+') { p++; } /* Some platform strtods accept hex floats; Python shouldn't (at the moment), so we check explicitly for strings starting with '0x'. */ if (*p == '0' && (*(p+1) == 'x' || *(p+1) == 'X')) goto invalid_string; /* Check that what's left begins with a digit or decimal point */ if (!Py_ISDIGIT(*p) && *p != '.') goto invalid_string; digits_pos = p; if (decimal_point[0] != '.' || decimal_point[1] != 0) { /* Look for a '.' in the input; if present, it'll need to be swapped for the current locale's decimal point before we call strtod. On the other hand, if we find the current locale's decimal point then the input is invalid. */ while (Py_ISDIGIT(*p)) p++; if (*p == '.') { decimal_point_pos = p++; /* locate end of number */ while (Py_ISDIGIT(*p)) p++; if (*p == 'e' || *p == 'E') p++; if (*p == '+' || *p == '-') p++; while (Py_ISDIGIT(*p)) p++; end = p; } else if (strncmp(p, decimal_point, decimal_point_len) == 0) /* Python bug #1417699 */ goto invalid_string; /* For the other cases, we need not convert the decimal point */ } if (decimal_point_pos) { char *copy, *c; /* Create a copy of the input, with the '.' converted to the locale-specific decimal point */ copy = (char *)PyMem_MALLOC(end - digits_pos + 1 + decimal_point_len); if (copy == NULL) { *endptr = (char *)nptr; errno = ENOMEM; return val; } c = copy; memcpy(c, digits_pos, decimal_point_pos - digits_pos); c += decimal_point_pos - digits_pos; memcpy(c, decimal_point, decimal_point_len); c += decimal_point_len; memcpy(c, decimal_point_pos + 1, end - (decimal_point_pos + 1)); c += end - (decimal_point_pos + 1); *c = 0; val = strtod(copy, &fail_pos); if (fail_pos) { if (fail_pos > decimal_point_pos) fail_pos = (char *)digits_pos + (fail_pos - copy) - (decimal_point_len - 1); else fail_pos = (char *)digits_pos + (fail_pos - copy); } PyMem_FREE(copy); } else { val = strtod(digits_pos, &fail_pos); } if (fail_pos == digits_pos) goto invalid_string; if (negate && fail_pos != nptr) val = -val; *endptr = fail_pos; return val; invalid_string: *endptr = (char*)nptr; errno = EINVAL; return -1.0; } #endif /* PyOS_string_to_double converts a null-terminated byte string s (interpreted as a string of ASCII characters) to a float. The string should not have leading or trailing whitespace. The conversion is independent of the current locale. If endptr is NULL, try to convert the whole string. Raise ValueError and return -1.0 if the string is not a valid representation of a floating-point number. If endptr is non-NULL, try to convert as much of the string as possible. If no initial segment of the string is the valid representation of a floating-point number then *endptr is set to point to the beginning of the string, -1.0 is returned and again ValueError is raised. On overflow (e.g., when trying to convert '1e500' on an IEEE 754 machine), if overflow_exception is NULL then +-Py_HUGE_VAL is returned, and no Python exception is raised. Otherwise, overflow_exception should point to a Python exception, this exception will be raised, -1.0 will be returned, and *endptr will point just past the end of the converted value. If any other failure occurs (for example lack of memory), -1.0 is returned and the appropriate Python exception will have been set. */ double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception) { double x, result=-1.0; char *fail_pos; errno = 0; PyFPE_START_PROTECT("PyOS_string_to_double", return -1.0) x = _PyOS_ascii_strtod(s, &fail_pos); PyFPE_END_PROTECT(x) if (errno == ENOMEM) { PyErr_NoMemory(); fail_pos = (char *)s; } else if (!endptr && (fail_pos == s || *fail_pos != '\0')) PyErr_Format(PyExc_ValueError, "could not convert string to float: " "%.200s", s); else if (fail_pos == s) PyErr_Format(PyExc_ValueError, "could not convert string to float: " "%.200s", s); else if (errno == ERANGE && fabs(x) >= 1.0 && overflow_exception) PyErr_Format(overflow_exception, "value too large to convert to float: " "%.200s", s); else result = x; if (endptr != NULL) *endptr = fail_pos; return result; } /* Remove underscores that follow the underscore placement rule from the string and then call the `innerfunc` function on the result. It should return a new object or NULL on exception. `what` is used for the error message emitted when underscores are detected that don't follow the rule. `arg` is an opaque pointer passed to the inner function. This is used to implement underscore-agnostic conversion for floats and complex numbers. */ PyObject * _Py_string_to_number_with_underscores( const char *s, Py_ssize_t orig_len, const char *what, PyObject *obj, void *arg, PyObject *(*innerfunc)(const char *, Py_ssize_t, void *)) { char prev; const char *p, *last; char *dup, *end; PyObject *result; assert(s[orig_len] == '\0'); if (strchr(s, '_') == NULL) { return innerfunc(s, orig_len, arg); } dup = PyMem_Malloc(orig_len + 1); if (dup == NULL) { return PyErr_NoMemory(); } end = dup; prev = '\0'; last = s + orig_len; for (p = s; *p; p++) { if (*p == '_') { /* Underscores are only allowed after digits. */ if (!(prev >= '0' && prev <= '9')) { goto error; } } else { *end++ = *p; /* Underscores are only allowed before digits. */ if (prev == '_' && !(*p >= '0' && *p <= '9')) { goto error; } } prev = *p; } /* Underscores are not allowed at the end. */ if (prev == '_') { goto error; } /* No embedded NULs allowed. */ if (p != last) { goto error; } *end = '\0'; result = innerfunc(dup, end - dup, arg); PyMem_Free(dup); return result; error: PyMem_Free(dup); PyErr_Format(PyExc_ValueError, "could not convert string to %s: " "%R", what, obj); return NULL; } #ifdef PY_NO_SHORT_FLOAT_REPR /* Given a string that may have a decimal point in the current locale, change it back to a dot. Since the string cannot get longer, no need for a maximum buffer size parameter. */ Py_LOCAL_INLINE(void) change_decimal_from_locale_to_dot(char* buffer) { struct lconv *locale_data = localeconv(); const char *decimal_point = locale_data->decimal_point; if (decimal_point[0] != '.' || decimal_point[1] != 0) { size_t decimal_point_len = strlen(decimal_point); if (*buffer == '+' || *buffer == '-') buffer++; while (Py_ISDIGIT(*buffer)) buffer++; if (strncmp(buffer, decimal_point, decimal_point_len) == 0) { *buffer = '.'; buffer++; if (decimal_point_len > 1) { /* buffer needs to get smaller */ size_t rest_len = strlen(buffer + (decimal_point_len - 1)); memmove(buffer, buffer + (decimal_point_len - 1), rest_len); buffer[rest_len] = 0; } } } } /* From the C99 standard, section 7.19.6: The exponent always contains at least two digits, and only as many more digits as necessary to represent the exponent. */ #define MIN_EXPONENT_DIGITS 2 /* Ensure that any exponent, if present, is at least MIN_EXPONENT_DIGITS in length. */ Py_LOCAL_INLINE(void) ensure_minimum_exponent_length(char* buffer, size_t buf_size) { char *p = strpbrk(buffer, "eE"); if (p && (*(p + 1) == '-' || *(p + 1) == '+')) { char *start = p + 2; int exponent_digit_cnt = 0; int leading_zero_cnt = 0; int in_leading_zeros = 1; int significant_digit_cnt; /* Skip over the exponent and the sign. */ p += 2; /* Find the end of the exponent, keeping track of leading zeros. */ while (*p && Py_ISDIGIT(*p)) { if (in_leading_zeros && *p == '0') ++leading_zero_cnt; if (*p != '0') in_leading_zeros = 0; ++p; ++exponent_digit_cnt; } significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt; if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) { /* If there are 2 exactly digits, we're done, regardless of what they contain */ } else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) { int extra_zeros_cnt; /* There are more than 2 digits in the exponent. See if we can delete some of the leading zeros */ if (significant_digit_cnt < MIN_EXPONENT_DIGITS) significant_digit_cnt = MIN_EXPONENT_DIGITS; extra_zeros_cnt = exponent_digit_cnt - significant_digit_cnt; /* Delete extra_zeros_cnt worth of characters from the front of the exponent */ assert(extra_zeros_cnt >= 0); /* Add one to significant_digit_cnt to copy the trailing 0 byte, thus setting the length */ memmove(start, start + extra_zeros_cnt, significant_digit_cnt + 1); } else { /* If there are fewer than 2 digits, add zeros until there are 2, if there's enough room */ int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt; if (start + zeros + exponent_digit_cnt + 1 < buffer + buf_size) { memmove(start + zeros, start, exponent_digit_cnt + 1); memset(start, '0', zeros); } } } } /* Remove trailing zeros after the decimal point from a numeric string; also remove the decimal point if all digits following it are zero. The numeric string must end in '\0', and should not have any leading or trailing whitespace. Assumes that the decimal point is '.'. */ Py_LOCAL_INLINE(void) remove_trailing_zeros(char *buffer) { char *old_fraction_end, *new_fraction_end, *end, *p; p = buffer; if (*p == '-' || *p == '+') /* Skip leading sign, if present */ ++p; while (Py_ISDIGIT(*p)) ++p; /* if there's no decimal point there's nothing to do */ if (*p++ != '.') return; /* scan any digits after the point */ while (Py_ISDIGIT(*p)) ++p; old_fraction_end = p; /* scan up to ending '\0' */ while (*p != '\0') p++; /* +1 to make sure that we move the null byte as well */ end = p+1; /* scan back from fraction_end, looking for removable zeros */ p = old_fraction_end; while (*(p-1) == '0') --p; /* and remove point if we've got that far */ if (*(p-1) == '.') --p; new_fraction_end = p; memmove(new_fraction_end, old_fraction_end, end-old_fraction_end); } /* Ensure that buffer has a decimal point in it. The decimal point will not be in the current locale, it will always be '.'. Don't add a decimal point if an exponent is present. Also, convert to exponential notation where adding a '.0' would produce too many significant digits (see issue 5864). Returns a pointer to the fixed buffer, or NULL on failure. */ Py_LOCAL_INLINE(char *) ensure_decimal_point(char* buffer, size_t buf_size, int precision) { int digit_count, insert_count = 0, convert_to_exp = 0; char *chars_to_insert, *digits_start; /* search for the first non-digit character */ char *p = buffer; if (*p == '-' || *p == '+') /* Skip leading sign, if present. I think this could only ever be '-', but it can't hurt to check for both. */ ++p; digits_start = p; while (*p && Py_ISDIGIT(*p)) ++p; digit_count = Py_SAFE_DOWNCAST(p - digits_start, Py_ssize_t, int); if (*p == '.') { if (Py_ISDIGIT(*(p+1))) { /* Nothing to do, we already have a decimal point and a digit after it */ } else { /* We have a decimal point, but no following digit. Insert a zero after the decimal. */ /* can't ever get here via PyOS_double_to_string */ assert(precision == -1); ++p; chars_to_insert = "0"; insert_count = 1; } } else if (!(*p == 'e' || *p == 'E')) { /* Don't add ".0" if we have an exponent. */ if (digit_count == precision) { /* issue 5864: don't add a trailing .0 in the case where the '%g'-formatted result already has as many significant digits as were requested. Switch to exponential notation instead. */ convert_to_exp = 1; /* no exponent, no point, and we shouldn't land here for infs and nans, so we must be at the end of the string. */ assert(*p == '\0'); } else { assert(precision == -1 || digit_count < precision); chars_to_insert = ".0"; insert_count = 2; } } if (insert_count) { size_t buf_len = strlen(buffer); if (buf_len + insert_count + 1 >= buf_size) { /* If there is not enough room in the buffer for the additional text, just skip it. It's not worth generating an error over. */ } else { memmove(p + insert_count, p, buffer + strlen(buffer) - p + 1); memcpy(p, chars_to_insert, insert_count); } } if (convert_to_exp) { int written; size_t buf_avail; p = digits_start; /* insert decimal point */ assert(digit_count >= 1); memmove(p+2, p+1, digit_count); /* safe, but overwrites nul */ p[1] = '.'; p += digit_count+1; assert(p <= buf_size+buffer); buf_avail = buf_size+buffer-p; if (buf_avail == 0) return NULL; /* Add exponent. It's okay to use lower case 'e': we only arrive here as a result of using the empty format code or repr/str builtins and those never want an upper case 'E' */ written = PyOS_snprintf(p, buf_avail, "e%+.02d", digit_count-1); if (!(0 <= written && written < Py_SAFE_DOWNCAST(buf_avail, size_t, int))) /* output truncated, or something else bad happened */ return NULL; remove_trailing_zeros(buffer); } return buffer; } /* see FORMATBUFLEN in unicodeobject.c */ #define FLOAT_FORMATBUFLEN 120 /** * _PyOS_ascii_formatd: * @buffer: A buffer to place the resulting string in * @buf_size: The length of the buffer. * @format: The printf()-style format to use for the * code to use for converting. * @d: The #gdouble to convert * @precision: The precision to use when formatting. * * Converts a #gdouble to a string, using the '.' as * decimal point. To format the number you pass in * a printf()-style format string. Allowed conversion * specifiers are 'e', 'E', 'f', 'F', 'g', 'G', and 'Z'. * * 'Z' is the same as 'g', except it always has a decimal and * at least one digit after the decimal. * * Return value: The pointer to the buffer with the converted string. * On failure returns NULL but does not set any Python exception. **/ static char * _PyOS_ascii_formatd(char *buffer, size_t buf_size, const char *format, double d, int precision) { char format_char; size_t format_len = strlen(format); /* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but also with at least one character past the decimal. */ char tmp_format[FLOAT_FORMATBUFLEN]; /* The last character in the format string must be the format char */ format_char = format[format_len - 1]; if (format[0] != '%') return NULL; /* I'm not sure why this test is here. It's ensuring that the format string after the first character doesn't have a single quote, a lowercase l, or a percent. This is the reverse of the commented-out test about 10 lines ago. */ if (strpbrk(format + 1, "'l%")) return NULL; /* Also curious about this function is that it accepts format strings like "%xg", which are invalid for floats. In general, the interface to this function is not very good, but changing it is difficult because it's a public API. */ if (!(format_char == 'e' || format_char == 'E' || format_char == 'f' || format_char == 'F' || format_char == 'g' || format_char == 'G' || format_char == 'Z')) return NULL; /* Map 'Z' format_char to 'g', by copying the format string and replacing the final char with a 'g' */ if (format_char == 'Z') { if (format_len + 1 >= sizeof(tmp_format)) { /* The format won't fit in our copy. Error out. In practice, this will never happen and will be detected by returning NULL */ return NULL; } strcpy(tmp_format, format); tmp_format[format_len - 1] = 'g'; format = tmp_format; } /* Have PyOS_snprintf do the hard work */ PyOS_snprintf(buffer, buf_size, format, d); /* Do various fixups on the return string */ /* Get the current locale, and find the decimal point string. Convert that string back to a dot. */ change_decimal_from_locale_to_dot(buffer); /* If an exponent exists, ensure that the exponent is at least MIN_EXPONENT_DIGITS digits, providing the buffer is large enough for the extra zeros. Also, if there are more than MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get back to MIN_EXPONENT_DIGITS */ ensure_minimum_exponent_length(buffer, buf_size); /* If format_char is 'Z', make sure we have at least one character after the decimal point (and make sure we have a decimal point); also switch to exponential notation in some edge cases where the extra character would produce more significant digits that we really want. */ if (format_char == 'Z') buffer = ensure_decimal_point(buffer, buf_size, precision); return buffer; } /* The fallback code to use if _Py_dg_dtoa is not available. */ char * PyOS_double_to_string(double val, char format_code, int precision, int flags, int *type) { char format[32]; Py_ssize_t bufsize; char *buf; int t, exp; int upper = 0; /* Validate format_code, and map upper and lower case */ switch (format_code) { case 'e': /* exponent */ case 'f': /* fixed */ case 'g': /* general */ break; case 'E': upper = 1; format_code = 'e'; break; case 'F': upper = 1; format_code = 'f'; break; case 'G': upper = 1; format_code = 'g'; break; case 'r': /* repr format */ /* Supplied precision is unused, must be 0. */ if (precision != 0) { PyErr_BadInternalCall(); return NULL; } /* The repr() precision (17 significant decimal digits) is the minimal number that is guaranteed to have enough precision so that if the number is read back in the exact same binary value is recreated. This is true for IEEE floating point by design, and also happens to work for all other modern hardware. */ precision = 17; format_code = 'g'; break; default: PyErr_BadInternalCall(); return NULL; } /* Here's a quick-and-dirty calculation to figure out how big a buffer we need. In general, for a finite float we need: 1 byte for each digit of the decimal significand, and 1 for a possible sign 1 for a possible decimal point 2 for a possible [eE][+-] 1 for each digit of the exponent; if we allow 19 digits total then we're safe up to exponents of 2**63. 1 for the trailing nul byte This gives a total of 24 + the number of digits in the significand, and the number of digits in the significand is: for 'g' format: at most precision, except possibly when precision == 0, when it's 1. for 'e' format: precision+1 for 'f' format: precision digits after the point, at least 1 before. To figure out how many digits appear before the point we have to examine the size of the number. If fabs(val) < 1.0 then there will be only one digit before the point. If fabs(val) >= 1.0, then there are at most 1+floor(log10(ceiling(fabs(val)))) digits before the point (where the 'ceiling' allows for the possibility that the rounding rounds the integer part of val up). A safe upper bound for the above quantity is 1+floor(exp/3), where exp is the unique integer such that 0.5 <= fabs(val)/2**exp < 1.0. This exp can be obtained from frexp. So we allow room for precision+1 digits for all formats, plus an extra floor(exp/3) digits for 'f' format. */ if (Py_IS_NAN(val) || Py_IS_INFINITY(val)) /* 3 for 'inf'/'nan', 1 for sign, 1 for '\0' */ bufsize = 5; else { bufsize = 25 + precision; if (format_code == 'f' && fabs(val) >= 1.0) { frexp(val, &exp); bufsize += exp/3; } } buf = PyMem_Malloc(bufsize); if (buf == NULL) { PyErr_NoMemory(); return NULL; } /* Handle nan and inf. */ if (Py_IS_NAN(val)) { strcpy(buf, "nan"); t = Py_DTST_NAN; } else if (Py_IS_INFINITY(val)) { if (copysign(1., val) == 1.) strcpy(buf, "inf"); else strcpy(buf, "-inf"); t = Py_DTST_INFINITE; } else { t = Py_DTST_FINITE; if (flags & Py_DTSF_ADD_DOT_0) format_code = 'Z'; PyOS_snprintf(format, sizeof(format), "%%%s.%i%c", (flags & Py_DTSF_ALT ? "#" : ""), precision, format_code); _PyOS_ascii_formatd(buf, bufsize, format, val, precision); } /* Add sign when requested. It's convenient (esp. when formatting complex numbers) to include a sign even for inf and nan. */ if (flags & Py_DTSF_SIGN && buf[0] != '-') { size_t len = strlen(buf); /* the bufsize calculations above should ensure that we've got space to add a sign */ assert((size_t)bufsize >= len+2); memmove(buf+1, buf, len+1); buf[0] = '+'; } if (upper) { /* Convert to upper case. */ char *p1; for (p1 = buf; *p1; p1++) *p1 = Py_TOUPPER(*p1); } if (type) *type = t; return buf; } #else /* _Py_dg_dtoa is available. */ /* I'm using a lookup table here so that I don't have to invent a non-locale specific way to convert to uppercase */ #define OFS_INF 0 #define OFS_NAN 1 #define OFS_E 2 /* The lengths of these are known to the code below, so don't change them */ static const char * const lc_float_strings[] = { "inf", "nan", "e", }; static const char * const uc_float_strings[] = { "INF", "NAN", "E", }; /* Convert a double d to a string, and return a PyMem_Malloc'd block of memory contain the resulting string. Arguments: d is the double to be converted format_code is one of 'e', 'f', 'g', 'r'. 'e', 'f' and 'g' correspond to '%e', '%f' and '%g'; 'r' corresponds to repr. mode is one of '0', '2' or '3', and is completely determined by format_code: 'e' and 'g' use mode 2; 'f' mode 3, 'r' mode 0. precision is the desired precision always_add_sign is nonzero if a '+' sign should be included for positive numbers add_dot_0_if_integer is nonzero if integers in non-exponential form should have ".0" added. Only applies to format codes 'r' and 'g'. use_alt_formatting is nonzero if alternative formatting should be used. Only applies to format codes 'e', 'f' and 'g'. For code 'g', at most one of use_alt_formatting and add_dot_0_if_integer should be nonzero. type, if non-NULL, will be set to one of these constants to identify the type of the 'd' argument: Py_DTST_FINITE Py_DTST_INFINITE Py_DTST_NAN Returns a PyMem_Malloc'd block of memory containing the resulting string, or NULL on error. If NULL is returned, the Python error has been set. */ static char * format_float_short(double d, char format_code, int mode, int precision, int always_add_sign, int add_dot_0_if_integer, int use_alt_formatting, const char * const *float_strings, int *type) { char *buf = NULL; char *p = NULL; Py_ssize_t bufsize = 0; char *digits, *digits_end; int decpt_as_int, sign, exp_len, exp = 0, use_exp = 0; Py_ssize_t decpt, digits_len, vdigits_start, vdigits_end; _Py_SET_53BIT_PRECISION_HEADER; /* _Py_dg_dtoa returns a digit string (no decimal point or exponent). Must be matched by a call to _Py_dg_freedtoa. */ _Py_SET_53BIT_PRECISION_START; digits = _Py_dg_dtoa(d, mode, precision, &decpt_as_int, &sign, &digits_end); _Py_SET_53BIT_PRECISION_END; decpt = (Py_ssize_t)decpt_as_int; if (digits == NULL) { /* The only failure mode is no memory. */ PyErr_NoMemory(); goto exit; } assert(digits_end != NULL && digits_end >= digits); digits_len = digits_end - digits; if (digits_len && !Py_ISDIGIT(digits[0])) { /* Infinities and nans here; adapt Gay's output, so convert Infinity to inf and NaN to nan, and ignore sign of nan. Then return. */ /* ignore the actual sign of a nan */ if (digits[0] == 'n' || digits[0] == 'N') sign = 0; /* We only need 5 bytes to hold the result "+inf\0" . */ bufsize = 5; /* Used later in an assert. */ buf = (char *)PyMem_Malloc(bufsize); if (buf == NULL) { PyErr_NoMemory(); goto exit; } p = buf; if (sign == 1) { *p++ = '-'; } else if (always_add_sign) { *p++ = '+'; } if (digits[0] == 'i' || digits[0] == 'I') { strncpy(p, float_strings[OFS_INF], 3); p += 3; if (type) *type = Py_DTST_INFINITE; } else if (digits[0] == 'n' || digits[0] == 'N') { strncpy(p, float_strings[OFS_NAN], 3); p += 3; if (type) *type = Py_DTST_NAN; } else { /* shouldn't get here: Gay's code should always return something starting with a digit, an 'I', or 'N' */ assert(0); } goto exit; } /* The result must be finite (not inf or nan). */ if (type) *type = Py_DTST_FINITE; /* We got digits back, format them. We may need to pad 'digits' either on the left or right (or both) with extra zeros, so in general the resulting string has the form [<sign>]<zeros><digits><zeros>[<exponent>] where either of the <zeros> pieces could be empty, and there's a decimal point that could appear either in <digits> or in the leading or trailing <zeros>. Imagine an infinite 'virtual' string vdigits, consisting of the string 'digits' (starting at index 0) padded on both the left and right with infinite strings of zeros. We want to output a slice vdigits[vdigits_start : vdigits_end] of this virtual string. Thus if vdigits_start < 0 then we'll end up producing some leading zeros; if vdigits_end > digits_len there will be trailing zeros in the output. The next section of code determines whether to use an exponent or not, figures out the position 'decpt' of the decimal point, and computes 'vdigits_start' and 'vdigits_end'. */ vdigits_end = digits_len; switch (format_code) { case 'e': use_exp = 1; vdigits_end = precision; break; case 'f': vdigits_end = decpt + precision; break; case 'g': if (decpt <= -4 || decpt > (add_dot_0_if_integer ? precision-1 : precision)) use_exp = 1; if (use_alt_formatting) vdigits_end = precision; break; case 'r': /* convert to exponential format at 1e16. We used to convert at 1e17, but that gives odd-looking results for some values when a 16-digit 'shortest' repr is padded with bogus zeros. For example, repr(2e16+8) would give 20000000000000010.0; the true value is 20000000000000008.0. */ if (decpt <= -4 || decpt > 16) use_exp = 1; break; default: PyErr_BadInternalCall(); goto exit; } /* if using an exponent, reset decimal point position to 1 and adjust exponent accordingly.*/ if (use_exp) { exp = (int)decpt - 1; decpt = 1; } /* ensure vdigits_start < decpt <= vdigits_end, or vdigits_start < decpt < vdigits_end if add_dot_0_if_integer and no exponent */ vdigits_start = decpt <= 0 ? decpt-1 : 0; if (!use_exp && add_dot_0_if_integer) vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1; else vdigits_end = vdigits_end > decpt ? vdigits_end : decpt; /* double check inequalities */ assert(vdigits_start <= 0 && 0 <= digits_len && digits_len <= vdigits_end); /* decimal point should be in (vdigits_start, vdigits_end] */ assert(vdigits_start < decpt && decpt <= vdigits_end); /* Compute an upper bound how much memory we need. This might be a few chars too long, but no big deal. */ bufsize = /* sign, decimal point and trailing 0 byte */ 3 + /* total digit count (including zero padding on both sides) */ (vdigits_end - vdigits_start) + /* exponent "e+100", max 3 numerical digits */ (use_exp ? 5 : 0); /* Now allocate the memory and initialize p to point to the start of it. */ buf = (char *)PyMem_Malloc(bufsize); if (buf == NULL) { PyErr_NoMemory(); goto exit; } p = buf; /* Add a negative sign if negative, and a plus sign if non-negative and always_add_sign is true. */ if (sign == 1) *p++ = '-'; else if (always_add_sign) *p++ = '+'; /* note that exactly one of the three 'if' conditions is true, so we include exactly one decimal point */ /* Zero padding on left of digit string */ if (decpt <= 0) { memset(p, '0', decpt-vdigits_start); p += decpt - vdigits_start; *p++ = '.'; memset(p, '0', 0-decpt); p += 0-decpt; } else { memset(p, '0', 0-vdigits_start); p += 0 - vdigits_start; } /* Digits, with included decimal point */ if (0 < decpt && decpt <= digits_len) { strncpy(p, digits, decpt-0); p += decpt-0; *p++ = '.'; strncpy(p, digits+decpt, digits_len-decpt); p += digits_len-decpt; } else { strncpy(p, digits, digits_len); p += digits_len; } /* And zeros on the right */ if (digits_len < decpt) { memset(p, '0', decpt-digits_len); p += decpt-digits_len; *p++ = '.'; memset(p, '0', vdigits_end-decpt); p += vdigits_end-decpt; } else { memset(p, '0', vdigits_end-digits_len); p += vdigits_end-digits_len; } /* Delete a trailing decimal pt unless using alternative formatting. */ if (p[-1] == '.' && !use_alt_formatting) p--; /* Now that we've done zero padding, add an exponent if needed. */ if (use_exp) { *p++ = float_strings[OFS_E][0]; exp_len = sprintf(p, "%+.02d", exp); p += exp_len; } exit: if (buf) { *p = '\0'; /* It's too late if this fails, as we've already stepped on memory that isn't ours. But it's an okay debugging test. */ assert(p-buf < bufsize); } if (digits) _Py_dg_freedtoa(digits); return buf; } char * PyOS_double_to_string(double val, char format_code, int precision, int flags, int *type) { const char * const *float_strings = lc_float_strings; int mode; /* Validate format_code, and map upper and lower case. Compute the mode and make any adjustments as needed. */ switch (format_code) { /* exponent */ case 'E': float_strings = uc_float_strings; format_code = 'e'; /* Fall through. */ case 'e': mode = 2; precision++; break; /* fixed */ case 'F': float_strings = uc_float_strings; format_code = 'f'; /* Fall through. */ case 'f': mode = 3; break; /* general */ case 'G': float_strings = uc_float_strings; format_code = 'g'; /* Fall through. */ case 'g': mode = 2; /* precision 0 makes no sense for 'g' format; interpret as 1 */ if (precision == 0) precision = 1; break; /* repr format */ case 'r': mode = 0; /* Supplied precision is unused, must be 0. */ if (precision != 0) { PyErr_BadInternalCall(); return NULL; } break; default: PyErr_BadInternalCall(); return NULL; } return format_float_short(val, format_code, mode, precision, flags & Py_DTSF_SIGN, flags & Py_DTSF_ADD_DOT_0, flags & Py_DTSF_ALT, float_strings, type); } #endif /* ifdef PY_NO_SHORT_FLOAT_REPR */
42,292
1,323
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/condvar.h
#ifndef _CONDVAR_H_ #define _CONDVAR_H_ #include "libc/time/time.h" /* clang-format off */ /* * Portable condition variable support for windows and pthreads. * Everything is inline, this header can be included where needed. * * APIs generally return 0 on success and non-zero on error, * and the caller needs to use its platform's error mechanism to * discover the error (errno, or GetLastError()) * * Note that some implementations cannot distinguish between a * condition variable wait time-out and successful wait. Most often * the difference is moot anyway since the wait condition must be * re-checked. * PyCOND_TIMEDWAIT, in addition to returning negative on error, * thus returns 0 on regular success, 1 on timeout * or 2 if it can't tell. * * There are at least two caveats with using these condition variables, * due to the fact that they may be emulated with Semaphores on * Windows: * 1) While PyCOND_SIGNAL() will wake up at least one thread, we * cannot currently guarantee that it will be one of the threads * already waiting in a PyCOND_WAIT() call. It _could_ cause * the wakeup of a subsequent thread to try a PyCOND_WAIT(), * including the thread doing the PyCOND_SIGNAL() itself. * The same applies to PyCOND_BROADCAST(), if N threads are waiting * then at least N threads will be woken up, but not necessarily * those already waiting. * For this reason, don't make the scheduling assumption that a * specific other thread will get the wakeup signal * 2) The _mutex_ must be held when calling PyCOND_SIGNAL() and * PyCOND_BROADCAST(). * While e.g. the posix standard strongly recommends that the mutex * associated with the condition variable is held when a * pthread_cond_signal() call is made, this is not a hard requirement, * although scheduling will not be "reliable" if it isn't. Here * the mutex is used for internal synchronization of the emulated * Condition Variable. */ #ifdef _POSIX_THREADS /* * POSIX support */ #define Py_HAVE_CONDVAR #define PyCOND_ADD_MICROSECONDS(tv, interval) \ do { /* TODO: add overflow and truncation checks */ \ tv.tv_usec += (long) interval; \ tv.tv_sec += tv.tv_usec / 1000000; \ tv.tv_usec %= 1000000; \ } while (0) /* We assume all modern POSIX systems have gettimeofday() */ #ifdef GETTIMEOFDAY_NO_TZ #define PyCOND_GETTIMEOFDAY(ptv) gettimeofday(ptv) #else #define PyCOND_GETTIMEOFDAY(ptv) gettimeofday(ptv, (struct timezone *)NULL) #endif /* The following functions return 0 on success, nonzero on error */ #define PyMUTEX_T pthread_mutex_t #define PyMUTEX_INIT(mut) pthread_mutex_init((mut), NULL) #define PyMUTEX_FINI(mut) pthread_mutex_destroy(mut) #define PyMUTEX_LOCK(mut) pthread_mutex_lock(mut) #define PyMUTEX_UNLOCK(mut) pthread_mutex_unlock(mut) #define PyCOND_T pthread_cond_t #define PyCOND_INIT(cond) pthread_cond_init((cond), NULL) #define PyCOND_FINI(cond) pthread_cond_destroy(cond) #define PyCOND_SIGNAL(cond) pthread_cond_signal(cond) #define PyCOND_BROADCAST(cond) pthread_cond_broadcast(cond) #define PyCOND_WAIT(cond, mut) pthread_cond_wait((cond), (mut)) /* return 0 for success, 1 on timeout, -1 on error */ Py_LOCAL_INLINE(int) PyCOND_TIMEDWAIT(PyCOND_T *cond, PyMUTEX_T *mut, long long us) { int r; struct timespec ts; struct timeval deadline; PyCOND_GETTIMEOFDAY(&deadline); PyCOND_ADD_MICROSECONDS(deadline, us); ts.tv_sec = deadline.tv_sec; ts.tv_nsec = deadline.tv_usec * 1000; r = pthread_cond_timedwait((cond), (mut), &ts); if (r == ETIMEDOUT) return 1; else if (r) return -1; else return 0; } #elif defined(NT_THREADS) /* * Windows (XP, 2003 server and later, as well as (hopefully) CE) support * * Emulated condition variables ones that work with XP and later, plus * example native support on VISTA and onwards. */ #define Py_HAVE_CONDVAR /* include windows if it hasn't been done before */ #define WIN32_LEAN_AND_MEAN /* options */ /* non-emulated condition variables are provided for those that want * to target Windows Vista. Modify this macro to enable them. */ #ifndef _PY_EMULATED_WIN_CV #define _PY_EMULATED_WIN_CV 1 /* use emulated condition variables */ #endif /* fall back to emulation if not targeting Vista */ #if !defined NTDDI_VISTA || NTDDI_VERSION < NTDDI_VISTA #undef _PY_EMULATED_WIN_CV #define _PY_EMULATED_WIN_CV 1 #endif #if _PY_EMULATED_WIN_CV /* The mutex is a CriticalSection object and The condition variables is emulated with the help of a semaphore. Semaphores are available on Windows XP (2003 server) and later. We use a Semaphore rather than an auto-reset event, because although an auto-resent event might appear to solve the lost-wakeup bug (race condition between releasing the outer lock and waiting) because it maintains state even though a wait hasn't happened, there is still a lost wakeup problem if more than one thread are interrupted in the critical place. A semaphore solves that, because its state is counted, not Boolean. Because it is ok to signal a condition variable with no one waiting, we need to keep track of the number of waiting threads. Otherwise, the semaphore's state could rise without bound. This also helps reduce the number of "spurious wakeups" that would otherwise happen. This implementation still has the problem that the threads woken with a "signal" aren't necessarily those that are already waiting. It corresponds to listing 2 in: http://birrell.org/andrew/papers/ImplementingCVs.pdf Generic emulations of the pthread_cond_* API using earlier Win32 functions can be found on the Web. The following read can be give background information to these issues, but the implementations are all broken in some way. http://www.cse.wustl.edu/~schmidt/win32-cv-1.html */ typedef CRITICAL_SECTION PyMUTEX_T; Py_LOCAL_INLINE(int) PyMUTEX_INIT(PyMUTEX_T *cs) { InitializeCriticalSection(cs); return 0; } Py_LOCAL_INLINE(int) PyMUTEX_FINI(PyMUTEX_T *cs) { DeleteCriticalSection(cs); return 0; } Py_LOCAL_INLINE(int) PyMUTEX_LOCK(PyMUTEX_T *cs) { EnterCriticalSection(cs); return 0; } Py_LOCAL_INLINE(int) PyMUTEX_UNLOCK(PyMUTEX_T *cs) { LeaveCriticalSection(cs); return 0; } /* The ConditionVariable object. From XP onwards it is easily emulated with * a Semaphore */ typedef struct _PyCOND_T { HANDLE sem; int waiting; /* to allow PyCOND_SIGNAL to be a no-op */ } PyCOND_T; Py_LOCAL_INLINE(int) PyCOND_INIT(PyCOND_T *cv) { /* A semaphore with a "large" max value, The positive value * is only needed to catch those "lost wakeup" events and * race conditions when a timed wait elapses. */ cv->sem = CreateSemaphore(NULL, 0, 100000, NULL); if (cv->sem==NULL) return -1; cv->waiting = 0; return 0; } Py_LOCAL_INLINE(int) PyCOND_FINI(PyCOND_T *cv) { return CloseHandle(cv->sem) ? 0 : -1; } /* this implementation can detect a timeout. Returns 1 on timeout, * 0 otherwise (and -1 on error) */ Py_LOCAL_INLINE(int) _PyCOND_WAIT_MS(PyCOND_T *cv, PyMUTEX_T *cs, DWORD ms) { DWORD wait; cv->waiting++; PyMUTEX_UNLOCK(cs); /* "lost wakeup bug" would occur if the caller were interrupted here, * but we are safe because we are using a semaphore which has an internal * count. */ wait = WaitForSingleObjectEx(cv->sem, ms, FALSE); PyMUTEX_LOCK(cs); if (wait != WAIT_OBJECT_0) --cv->waiting; /* Here we have a benign race condition with PyCOND_SIGNAL. * When failure occurs or timeout, it is possible that * PyCOND_SIGNAL also decrements this value * and signals releases the mutex. This is benign because it * just means an extra spurious wakeup for a waiting thread. * ('waiting' corresponds to the semaphore's "negative" count and * we may end up with e.g. (waiting == -1 && sem.count == 1). When * a new thread comes along, it will pass right throuhgh, having * adjusted it to (waiting == 0 && sem.count == 0). */ if (wait == WAIT_FAILED) return -1; /* return 0 on success, 1 on timeout */ return wait != WAIT_OBJECT_0; } Py_LOCAL_INLINE(int) PyCOND_WAIT(PyCOND_T *cv, PyMUTEX_T *cs) { int result = _PyCOND_WAIT_MS(cv, cs, INFINITE); return result >= 0 ? 0 : result; } Py_LOCAL_INLINE(int) PyCOND_TIMEDWAIT(PyCOND_T *cv, PyMUTEX_T *cs, long long us) { return _PyCOND_WAIT_MS(cv, cs, (DWORD)(us/1000)); } Py_LOCAL_INLINE(int) PyCOND_SIGNAL(PyCOND_T *cv) { /* this test allows PyCOND_SIGNAL to be a no-op unless required * to wake someone up, thus preventing an unbounded increase of * the semaphore's internal counter. */ if (cv->waiting > 0) { /* notifying thread decreases the cv->waiting count so that * a delay between notify and actual wakeup of the target thread * doesn't cause a number of extra ReleaseSemaphore calls. */ cv->waiting--; return ReleaseSemaphore(cv->sem, 1, NULL) ? 0 : -1; } return 0; } Py_LOCAL_INLINE(int) PyCOND_BROADCAST(PyCOND_T *cv) { int waiting = cv->waiting; if (waiting > 0) { cv->waiting = 0; return ReleaseSemaphore(cv->sem, waiting, NULL) ? 0 : -1; } return 0; } #else /* Use native Win7 primitives if build target is Win7 or higher */ /* SRWLOCK is faster and better than CriticalSection */ typedef SRWLOCK PyMUTEX_T; Py_LOCAL_INLINE(int) PyMUTEX_INIT(PyMUTEX_T *cs) { InitializeSRWLock(cs); return 0; } Py_LOCAL_INLINE(int) PyMUTEX_FINI(PyMUTEX_T *cs) { return 0; } Py_LOCAL_INLINE(int) PyMUTEX_LOCK(PyMUTEX_T *cs) { AcquireSRWLockExclusive(cs); return 0; } Py_LOCAL_INLINE(int) PyMUTEX_UNLOCK(PyMUTEX_T *cs) { ReleaseSRWLockExclusive(cs); return 0; } typedef CONDITION_VARIABLE PyCOND_T; Py_LOCAL_INLINE(int) PyCOND_INIT(PyCOND_T *cv) { InitializeConditionVariable(cv); return 0; } Py_LOCAL_INLINE(int) PyCOND_FINI(PyCOND_T *cv) { return 0; } Py_LOCAL_INLINE(int) PyCOND_WAIT(PyCOND_T *cv, PyMUTEX_T *cs) { return SleepConditionVariableSRW(cv, cs, INFINITE, 0) ? 0 : -1; } /* This implementation makes no distinction about timeouts. Signal * 2 to indicate that we don't know. */ Py_LOCAL_INLINE(int) PyCOND_TIMEDWAIT(PyCOND_T *cv, PyMUTEX_T *cs, long long us) { return SleepConditionVariableSRW(cv, cs, (DWORD)(us/1000), 0) ? 2 : -1; } Py_LOCAL_INLINE(int) PyCOND_SIGNAL(PyCOND_T *cv) { WakeConditionVariable(cv); return 0; } Py_LOCAL_INLINE(int) PyCOND_BROADCAST(PyCOND_T *cv) { WakeAllConditionVariable(cv); return 0; } #endif /* _PY_EMULATED_WIN_CV */ #endif /* _POSIX_THREADS, NT_THREADS */ #endif /* _CONDVAR_H_ */
10,896
376
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/getplatform.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ /* clang-format off */ const char * Py_GetPlatform(void) { return "cosmo"; }
895
14
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/initimport.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/internal.h" #include "libc/str/locale.h" #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/codecs.h" #include "third_party/python/Include/cosmo.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pymem.h" #include "third_party/python/Include/pystate.h" #include "third_party/python/Include/pythonrun.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ PYTHON_PROVIDE("_frozen_importlib"); PYTHON_PROVIDE("_frozen_importlib_external"); void _Py_InitImport(PyInterpreterState *interp, PyObject *sysmod) { PyObject *importlib; PyObject *impmod; PyObject *cosmomod; PyObject *sys_modules; PyObject *value; /* Import _importlib through its frozen version, _frozen_importlib. */ if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) { Py_FatalError("Py_Initialize: can't import _frozen_importlib"); } else if (Py_VerboseFlag) { PySys_FormatStderr("import _frozen_importlib # frozen\n"); } importlib = PyImport_AddModule("_frozen_importlib"); if (importlib == NULL) { Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from " "sys.modules"); } interp->importlib = importlib; Py_INCREF(interp->importlib); interp->import_func = PyDict_GetItemString(interp->builtins, "__import__"); if (interp->import_func == NULL) Py_FatalError("Py_Initialize: __import__ not found"); Py_INCREF(interp->import_func); /* Import the _imp module */ impmod = PyInit_imp(); if (impmod == NULL) { Py_FatalError("Py_Initialize: can't import _imp"); } else if (Py_VerboseFlag) { PySys_FormatStderr("import _imp # builtin\n"); } sys_modules = PyImport_GetModuleDict(); if (Py_VerboseFlag) { PySys_FormatStderr("import sys # builtin\n"); } if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) { Py_FatalError("Py_Initialize: can't save _imp to sys.modules"); } /* Install importlib as the implementation of import */ value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod); if (value == NULL) { PyErr_Print(); Py_FatalError("Py_Initialize: importlib install failed"); } Py_DECREF(value); Py_DECREF(impmod); }
3,486
82
jart/cosmopolitan
false
cosmopolitan/third_party/python/Python/_warnings.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Python 3 │ │ https://docs.python.org/3/license.html │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "third_party/python/Include/abstract.h" #include "third_party/python/Include/boolobject.h" #include "third_party/python/Include/dictobject.h" #include "third_party/python/Include/fileobject.h" #include "third_party/python/Include/frameobject.h" #include "third_party/python/Include/import.h" #include "third_party/python/Include/listobject.h" #include "third_party/python/Include/longobject.h" #include "third_party/python/Include/modsupport.h" #include "third_party/python/Include/object.h" #include "third_party/python/Include/pyctype.h" #include "third_party/python/Include/pydebug.h" #include "third_party/python/Include/pyerrors.h" #include "third_party/python/Include/pylifecycle.h" #include "third_party/python/Include/pymacro.h" #include "third_party/python/Include/sysmodule.h" #include "third_party/python/Include/traceback.h" #include "third_party/python/Include/tupleobject.h" #include "third_party/python/Include/unicodeobject.h" #include "third_party/python/Include/yoink.h" /* clang-format off */ PYTHON_PROVIDE("_warnings"); #define MODULE_NAME "_warnings" PyDoc_STRVAR(warnings__doc__, MODULE_NAME " provides basic warning filtering support.\n" "It is a helper module to speed up interpreter start-up."); /* Both 'filters' and 'onceregistry' can be set in warnings.py; get_warnings_attr() will reset these variables accordingly. */ static PyObject *_filters; /* List */ static PyObject *_once_registry; /* Dict */ static PyObject *_default_action; /* String */ static long _filters_version; _Py_IDENTIFIER(argv); _Py_IDENTIFIER(stderr); static int check_matched(PyObject *obj, PyObject *arg) { PyObject *result; _Py_IDENTIFIER(match); int rc; if (obj == Py_None) return 1; result = _PyObject_CallMethodId(obj, &PyId_match, "O", arg); if (result == NULL) return -1; rc = PyObject_IsTrue(result); Py_DECREF(result); return rc; } /* Returns a new reference. A NULL return value can mean false or an error. */ static PyObject * get_warnings_attr(const char *attr, int try_import) { static PyObject *warnings_str = NULL; PyObject *all_modules; PyObject *warnings_module, *obj; if (warnings_str == NULL) { warnings_str = PyUnicode_InternFromString("warnings"); if (warnings_str == NULL) return NULL; } /* don't try to import after the start of the Python finallization */ if (try_import && _Py_Finalizing == NULL) { warnings_module = PyImport_Import(warnings_str); if (warnings_module == NULL) { /* Fallback to the C implementation if we cannot get the Python implementation */ PyErr_Clear(); return NULL; } } else { /* if we're so late into Python finalization that the module dict is gone, then we can't even use PyImport_GetModule without triggering an interpreter abort. */ if (!PyThreadState_GET()->interp->modules) { return NULL; } all_modules = PyImport_GetModuleDict(); warnings_module = PyDict_GetItem(all_modules, warnings_str); if (warnings_module == NULL) return NULL; Py_INCREF(warnings_module); } if (!PyObject_HasAttrString(warnings_module, attr)) { Py_DECREF(warnings_module); return NULL; } obj = PyObject_GetAttrString(warnings_module, attr); Py_DECREF(warnings_module); return obj; } static PyObject * get_once_registry(void) { PyObject *registry; registry = get_warnings_attr("onceregistry", 0); if (registry == NULL) { if (PyErr_Occurred()) return NULL; return _once_registry; } if (!PyDict_Check(registry)) { PyErr_SetString(PyExc_TypeError, "warnings.onceregistry must be a dict"); Py_DECREF(registry); return NULL; } Py_DECREF(_once_registry); _once_registry = registry; return registry; } static PyObject * get_default_action(void) { PyObject *default_action; default_action = get_warnings_attr("defaultaction", 0); if (default_action == NULL) { if (PyErr_Occurred()) { return NULL; } return _default_action; } if (!PyUnicode_Check(default_action)) { PyErr_Format(PyExc_TypeError, MODULE_NAME ".defaultaction must be a string, " "not '%.200s'", Py_TYPE(default_action)->tp_name); Py_DECREF(default_action); return NULL; } Py_DECREF(_default_action); _default_action = default_action; return default_action; } /* The item is a new reference. */ static PyObject* get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno, PyObject *module, PyObject **item) { PyObject *action; Py_ssize_t i; PyObject *warnings_filters; warnings_filters = get_warnings_attr("filters", 0); if (warnings_filters == NULL) { if (PyErr_Occurred()) return NULL; } else { Py_DECREF(_filters); _filters = warnings_filters; } if (_filters == NULL || !PyList_Check(_filters)) { PyErr_SetString(PyExc_ValueError, MODULE_NAME ".filters must be a list"); return NULL; } /* _filters could change while we are iterating over it. */ for (i = 0; i < PyList_GET_SIZE(_filters); i++) { PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj; Py_ssize_t ln; int is_subclass, good_msg, good_mod; tmp_item = PyList_GET_ITEM(_filters, i); if (!PyTuple_Check(tmp_item) || PyTuple_GET_SIZE(tmp_item) != 5) { PyErr_Format(PyExc_ValueError, MODULE_NAME ".filters item %zd isn't a 5-tuple", i); return NULL; } /* Python code: action, msg, cat, mod, ln = item */ Py_INCREF(tmp_item); action = PyTuple_GET_ITEM(tmp_item, 0); msg = PyTuple_GET_ITEM(tmp_item, 1); cat = PyTuple_GET_ITEM(tmp_item, 2); mod = PyTuple_GET_ITEM(tmp_item, 3); ln_obj = PyTuple_GET_ITEM(tmp_item, 4); if (!PyUnicode_Check(action)) { PyErr_Format(PyExc_TypeError, "action must be a string, not '%.200s'", Py_TYPE(action)->tp_name); Py_DECREF(tmp_item); return NULL; } good_msg = check_matched(msg, text); if (good_msg == -1) { Py_DECREF(tmp_item); return NULL; } good_mod = check_matched(mod, module); if (good_mod == -1) { Py_DECREF(tmp_item); return NULL; } is_subclass = PyObject_IsSubclass(category, cat); if (is_subclass == -1) { Py_DECREF(tmp_item); return NULL; } ln = PyLong_AsSsize_t(ln_obj); if (ln == -1 && PyErr_Occurred()) { Py_DECREF(tmp_item); return NULL; } if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln)) { *item = tmp_item; return action; } Py_DECREF(tmp_item); } action = get_default_action(); if (action != NULL) { Py_INCREF(Py_None); *item = Py_None; return action; } return NULL; } static int already_warned(PyObject *registry, PyObject *key, int should_set) { PyObject *version_obj, *already_warned; _Py_IDENTIFIER(version); if (key == NULL) return -1; version_obj = _PyDict_GetItemId(registry, &PyId_version); if (version_obj == NULL || !PyLong_CheckExact(version_obj) || PyLong_AsLong(version_obj) != _filters_version) { if (PyErr_Occurred()) { return -1; } PyDict_Clear(registry); version_obj = PyLong_FromLong(_filters_version); if (version_obj == NULL) return -1; if (_PyDict_SetItemId(registry, &PyId_version, version_obj) < 0) { Py_DECREF(version_obj); return -1; } Py_DECREF(version_obj); } else { already_warned = PyDict_GetItem(registry, key); if (already_warned != NULL) { int rc = PyObject_IsTrue(already_warned); if (rc != 0) return rc; } } /* This warning wasn't found in the registry, set it. */ if (should_set) return PyDict_SetItem(registry, key, Py_True); return 0; } /* New reference. */ static PyObject * normalize_module(PyObject *filename) { PyObject *module; int kind; void *data; Py_ssize_t len; len = PyUnicode_GetLength(filename); if (len < 0) return NULL; if (len == 0) return PyUnicode_FromString("<unknown>"); kind = PyUnicode_KIND(filename); data = PyUnicode_DATA(filename); /* if filename.endswith(".py"): */ if (len >= 3 && PyUnicode_READ(kind, data, len-3) == '.' && PyUnicode_READ(kind, data, len-2) == 'p' && PyUnicode_READ(kind, data, len-1) == 'y') { module = PyUnicode_Substring(filename, 0, len-3); } else { module = filename; Py_INCREF(module); } return module; } static int update_registry(PyObject *registry, PyObject *text, PyObject *category, int add_zero) { PyObject *altkey, *zero = NULL; int rc; if (add_zero) { zero = PyLong_FromLong(0); if (zero == NULL) return -1; altkey = PyTuple_Pack(3, text, category, zero); } else altkey = PyTuple_Pack(2, text, category); rc = already_warned(registry, altkey, 1); Py_XDECREF(zero); Py_XDECREF(altkey); return rc; } static void show_warning(PyObject *filename, int lineno, PyObject *text, PyObject *category, PyObject *sourceline) { PyObject *f_stderr; PyObject *name; char lineno_str[128]; _Py_IDENTIFIER(__name__); PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno); name = _PyObject_GetAttrId(category, &PyId___name__); if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */ goto error; f_stderr = _PySys_GetObjectId(&PyId_stderr); if (f_stderr == NULL) { fprintf(stderr, "lost sys.stderr\n"); goto error; } /* Print "filename:lineno: category: text\n" */ if (PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW) < 0) goto error; if (PyFile_WriteString(lineno_str, f_stderr) < 0) goto error; if (PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW) < 0) goto error; if (PyFile_WriteString(": ", f_stderr) < 0) goto error; if (PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW) < 0) goto error; if (PyFile_WriteString("\n", f_stderr) < 0) goto error; Py_CLEAR(name); /* Print " source_line\n" */ if (sourceline) { int kind; void *data; Py_ssize_t i, len; Py_UCS4 ch; PyObject *truncated; if (PyUnicode_READY(sourceline) < 1) goto error; kind = PyUnicode_KIND(sourceline); data = PyUnicode_DATA(sourceline); len = PyUnicode_GET_LENGTH(sourceline); for (i=0; i<len; i++) { ch = PyUnicode_READ(kind, data, i); if (ch != ' ' && ch != '\t' && ch != '\014') break; } truncated = PyUnicode_Substring(sourceline, i, len); if (truncated == NULL) goto error; PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW); Py_DECREF(truncated); PyFile_WriteString("\n", f_stderr); } else { _Py_DisplaySourceLine(f_stderr, filename, lineno, 2); } error: Py_XDECREF(name); PyErr_Clear(); } static int call_show_warning(PyObject *category, PyObject *text, PyObject *message, PyObject *filename, int lineno, PyObject *lineno_obj, PyObject *sourceline, PyObject *source) { PyObject *show_fn, *msg, *res, *warnmsg_cls = NULL; /* If the source parameter is set, try to get the Python implementation. The Python implementation is able to log the traceback where the source was allocated, whereas the C implementation doesnt. */ show_fn = get_warnings_attr("_showwarnmsg", source != NULL); if (show_fn == NULL) { if (PyErr_Occurred()) return -1; show_warning(filename, lineno, text, category, sourceline); return 0; } if (!PyCallable_Check(show_fn)) { PyErr_SetString(PyExc_TypeError, "warnings._showwarnmsg() must be set to a callable"); goto error; } warnmsg_cls = get_warnings_attr("WarningMessage", 0); if (warnmsg_cls == NULL) { PyErr_SetString(PyExc_RuntimeError, "unable to get warnings.WarningMessage"); goto error; } msg = PyObject_CallFunctionObjArgs(warnmsg_cls, message, category, filename, lineno_obj, Py_None, Py_None, source, NULL); Py_DECREF(warnmsg_cls); if (msg == NULL) goto error; res = PyObject_CallFunctionObjArgs(show_fn, msg, NULL); Py_DECREF(show_fn); Py_DECREF(msg); if (res == NULL) return -1; Py_DECREF(res); return 0; error: Py_XDECREF(show_fn); return -1; } static PyObject * warn_explicit(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry, PyObject *sourceline, PyObject *source) { PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL; PyObject *item = NULL; PyObject *action; int rc; /* module can be None if a warning is emitted late during Python shutdown. In this case, the Python warnings module was probably unloaded, filters are no more available to choose as action. It is safer to ignore the warning and do nothing. */ if (module == Py_None) Py_RETURN_NONE; if (registry && !PyDict_Check(registry) && (registry != Py_None)) { PyErr_SetString(PyExc_TypeError, "'registry' must be a dict or None"); return NULL; } /* Normalize module. */ if (module == NULL) { module = normalize_module(filename); if (module == NULL) return NULL; } else Py_INCREF(module); /* Normalize message. */ Py_INCREF(message); /* DECREF'ed in cleanup. */ rc = PyObject_IsInstance(message, PyExc_Warning); if (rc == -1) { goto cleanup; } if (rc == 1) { text = PyObject_Str(message); if (text == NULL) goto cleanup; category = (PyObject*)message->ob_type; } else { text = message; message = PyObject_CallFunction(category, "O", message); if (message == NULL) goto cleanup; } lineno_obj = PyLong_FromLong(lineno); if (lineno_obj == NULL) goto cleanup; /* Create key. */ key = PyTuple_Pack(3, text, category, lineno_obj); if (key == NULL) goto cleanup; if ((registry != NULL) && (registry != Py_None)) { rc = already_warned(registry, key, 0); if (rc == -1) goto cleanup; else if (rc == 1) goto return_none; /* Else this warning hasn't been generated before. */ } action = get_filter(category, text, lineno, module, &item); if (action == NULL) goto cleanup; if (_PyUnicode_EqualToASCIIString(action, "error")) { PyErr_SetObject(category, message); goto cleanup; } /* Store in the registry that we've been here, *except* when the action is "always". */ rc = 0; if (!_PyUnicode_EqualToASCIIString(action, "always")) { if (registry != NULL && registry != Py_None && PyDict_SetItem(registry, key, Py_True) < 0) goto cleanup; else if (_PyUnicode_EqualToASCIIString(action, "ignore")) goto return_none; else if (_PyUnicode_EqualToASCIIString(action, "once")) { if (registry == NULL || registry == Py_None) { registry = get_once_registry(); if (registry == NULL) goto cleanup; } /* _once_registry[(text, category)] = 1 */ rc = update_registry(registry, text, category, 0); } else if (_PyUnicode_EqualToASCIIString(action, "module")) { /* registry[(text, category, 0)] = 1 */ if (registry != NULL && registry != Py_None) rc = update_registry(registry, text, category, 0); } else if (!_PyUnicode_EqualToASCIIString(action, "default")) { PyErr_Format(PyExc_RuntimeError, "Unrecognized action (%R) in warnings.filters:\n %R", action, item); goto cleanup; } } if (rc == 1) /* Already warned for this module. */ goto return_none; if (rc == 0) { if (call_show_warning(category, text, message, filename, lineno, lineno_obj, sourceline, source) < 0) goto cleanup; } else /* if (rc == -1) */ goto cleanup; return_none: result = Py_None; Py_INCREF(result); cleanup: Py_XDECREF(item); Py_XDECREF(key); Py_XDECREF(text); Py_XDECREF(lineno_obj); Py_DECREF(module); Py_XDECREF(message); return result; /* Py_None or NULL. */ } static int is_internal_frame(PyFrameObject *frame) { static PyObject *importlib_string = NULL; static PyObject *bootstrap_string = NULL; PyObject *filename; int contains; if (importlib_string == NULL) { importlib_string = PyUnicode_FromString("importlib"); if (importlib_string == NULL) { return 0; } bootstrap_string = PyUnicode_FromString("_bootstrap"); if (bootstrap_string == NULL) { Py_DECREF(importlib_string); return 0; } Py_INCREF(importlib_string); Py_INCREF(bootstrap_string); } if (frame == NULL || frame->f_code == NULL || frame->f_code->co_filename == NULL) { return 0; } filename = frame->f_code->co_filename; if (!PyUnicode_Check(filename)) { return 0; } contains = PyUnicode_Contains(filename, importlib_string); if (contains < 0) { return 0; } else if (contains > 0) { contains = PyUnicode_Contains(filename, bootstrap_string); if (contains < 0) { return 0; } else if (contains > 0) { return 1; } } return 0; } static PyFrameObject * next_external_frame(PyFrameObject *frame) { do { frame = frame->f_back; } while (frame != NULL && is_internal_frame(frame)); return frame; } /* filename, module, and registry are new refs, globals is borrowed */ /* Returns 0 on error (no new refs), 1 on success */ static int setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno, PyObject **module, PyObject **registry) { PyObject *globals; /* Setup globals and lineno. */ PyFrameObject *f = PyThreadState_GET()->frame; // Stack level comparisons to Python code is off by one as there is no // warnings-related stack level to avoid. if (stack_level <= 0 || is_internal_frame(f)) { while (--stack_level > 0 && f != NULL) { f = f->f_back; } } else { while (--stack_level > 0 && f != NULL) { f = next_external_frame(f); } } if (f == NULL) { globals = PyThreadState_Get()->interp->sysdict; *lineno = 1; } else { globals = f->f_globals; *lineno = PyFrame_GetLineNumber(f); } *module = NULL; /* Setup registry. */ assert(globals != NULL); assert(PyDict_Check(globals)); *registry = PyDict_GetItemString(globals, "__warningregistry__"); if (*registry == NULL) { int rc; *registry = PyDict_New(); if (*registry == NULL) return 0; rc = PyDict_SetItemString(globals, "__warningregistry__", *registry); if (rc < 0) goto handle_error; } else Py_INCREF(*registry); /* Setup module. */ *module = PyDict_GetItemString(globals, "__name__"); if (*module == Py_None || (*module != NULL && PyUnicode_Check(*module))) { Py_INCREF(*module); } else { *module = PyUnicode_FromString("<string>"); if (*module == NULL) goto handle_error; } /* Setup filename. */ *filename = PyDict_GetItemString(globals, "__file__"); if (*filename != NULL && PyUnicode_Check(*filename)) { Py_ssize_t len; int kind; void *data; if (PyUnicode_READY(*filename)) goto handle_error; len = PyUnicode_GetLength(*filename); kind = PyUnicode_KIND(*filename); data = PyUnicode_DATA(*filename); #define ascii_lower(c) ((c <= 127) ? Py_TOLOWER(c) : 0) /* if filename.lower().endswith(".pyc"): */ if (len >= 4 && PyUnicode_READ(kind, data, len-4) == '.' && ascii_lower(PyUnicode_READ(kind, data, len-3)) == 'p' && ascii_lower(PyUnicode_READ(kind, data, len-2)) == 'y' && ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'c') { *filename = PyUnicode_Substring(*filename, 0, PyUnicode_GET_LENGTH(*filename)-1); if (*filename == NULL) goto handle_error; } else Py_INCREF(*filename); } else { *filename = NULL; if (*module != Py_None && _PyUnicode_EqualToASCIIString(*module, "__main__")) { PyObject *argv = _PySys_GetObjectId(&PyId_argv); /* PyList_Check() is needed because sys.argv is set to None during Python finalization */ if (argv != NULL && PyList_Check(argv) && PyList_Size(argv) > 0) { int is_true; *filename = PyList_GetItem(argv, 0); Py_INCREF(*filename); /* If sys.argv[0] is false, then use '__main__'. */ is_true = PyObject_IsTrue(*filename); if (is_true < 0) { Py_DECREF(*filename); goto handle_error; } else if (!is_true) { Py_SETREF(*filename, PyUnicode_FromString("__main__")); if (*filename == NULL) goto handle_error; } } else { /* embedded interpreters don't have sys.argv, see bug #839151 */ *filename = PyUnicode_FromString("__main__"); if (*filename == NULL) goto handle_error; } } if (*filename == NULL) { *filename = *module; Py_INCREF(*filename); } } return 1; handle_error: /* filename not XDECREF'ed here as there is no way to jump here with a dangling reference. */ Py_XDECREF(*registry); Py_XDECREF(*module); return 0; } static PyObject * get_category(PyObject *message, PyObject *category) { int rc; /* Get category. */ rc = PyObject_IsInstance(message, PyExc_Warning); if (rc == -1) return NULL; if (rc == 1) category = (PyObject*)message->ob_type; else if (category == NULL || category == Py_None) category = PyExc_UserWarning; /* Validate category. */ rc = PyObject_IsSubclass(category, PyExc_Warning); /* category is not a subclass of PyExc_Warning or PyObject_IsSubclass raised an error */ if (rc == -1 || rc == 0) { PyErr_Format(PyExc_TypeError, "category must be a Warning subclass, not '%s'", Py_TYPE(category)->tp_name); return NULL; } return category; } static PyObject * do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level, PyObject *source) { PyObject *filename, *module, *registry, *res; int lineno; if (!setup_context(stack_level, &filename, &lineno, &module, &registry)) return NULL; res = warn_explicit(category, message, filename, lineno, module, registry, NULL, source); Py_DECREF(filename); Py_DECREF(registry); Py_DECREF(module); return res; } static PyObject * warnings_warn(PyObject *self, PyObject *args, PyObject *kwds) { static char *kw_list[] = {"message", "category", "stacklevel", "source", NULL}; PyObject *message, *category = NULL, *source = NULL; Py_ssize_t stack_level = 1; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OnO:warn", kw_list, &message, &category, &stack_level, &source)) return NULL; category = get_category(message, category); if (category == NULL) return NULL; return do_warn(message, category, stack_level, source); } static PyObject * warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwd_list[] = {"message", "category", "filename", "lineno", "module", "registry", "module_globals", "source", 0}; PyObject *message; PyObject *category; PyObject *filename; int lineno; PyObject *module = NULL; PyObject *registry = NULL; PyObject *module_globals = NULL; PyObject *sourceobj = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOUi|OOOO:warn_explicit", kwd_list, &message, &category, &filename, &lineno, &module, &registry, &module_globals, &sourceobj)) return NULL; if (module_globals) { _Py_IDENTIFIER(get_source); PyObject *tmp; PyObject *loader; PyObject *module_name; PyObject *source; PyObject *source_list; PyObject *source_line; PyObject *returned; if ((tmp = _PyUnicode_FromId(&PyId_get_source)) == NULL) return NULL; /* Check/get the requisite pieces needed for the loader. */ loader = PyDict_GetItemString(module_globals, "__loader__"); module_name = PyDict_GetItemString(module_globals, "__name__"); if (loader == NULL || module_name == NULL) goto standard_call; /* Make sure the loader implements the optional get_source() method. */ if (!_PyObject_HasAttrId(loader, &PyId_get_source)) goto standard_call; /* Call get_source() to get the source code. */ source = PyObject_CallMethodObjArgs(loader, PyId_get_source.object, module_name, NULL); if (!source) return NULL; else if (source == Py_None) { Py_DECREF(Py_None); goto standard_call; } /* Split the source into lines. */ source_list = PyUnicode_Splitlines(source, 0); Py_DECREF(source); if (!source_list) return NULL; /* Get the source line. */ source_line = PyList_GetItem(source_list, lineno-1); if (!source_line) { Py_DECREF(source_list); return NULL; } /* Handle the warning. */ returned = warn_explicit(category, message, filename, lineno, module, registry, source_line, sourceobj); Py_DECREF(source_list); return returned; } standard_call: return warn_explicit(category, message, filename, lineno, module, registry, NULL, sourceobj); } static PyObject * warnings_filters_mutated(PyObject *self, PyObject *args) { _filters_version++; Py_RETURN_NONE; } /* Function to issue a warning message; may raise an exception. */ static int warn_unicode(PyObject *category, PyObject *message, Py_ssize_t stack_level, PyObject *source) { PyObject *res; if (category == NULL) category = PyExc_RuntimeWarning; res = do_warn(message, category, stack_level, source); if (res == NULL) return -1; Py_DECREF(res); return 0; } static int _PyErr_WarnFormatV(PyObject *source, PyObject *category, Py_ssize_t stack_level, const char *format, va_list vargs) { PyObject *message; int res; message = PyUnicode_FromFormatV(format, vargs); if (message == NULL) return -1; res = warn_unicode(category, message, stack_level, source); Py_DECREF(message); return res; } int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...) { int res; va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, format); #else va_start(vargs); #endif res = _PyErr_WarnFormatV(NULL, category, stack_level, format, vargs); va_end(vargs); return res; } int PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level, const char *format, ...) { int res; va_list vargs; #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, format); #else va_start(vargs); #endif res = _PyErr_WarnFormatV(source, PyExc_ResourceWarning, stack_level, format, vargs); va_end(vargs); return res; } int PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level) { int ret; PyObject *message = PyUnicode_FromString(text); if (message == NULL) return -1; ret = warn_unicode(category, message, stack_level, NULL); Py_DECREF(message); return ret; } /* PyErr_Warn is only for backwards compatibility and will be removed. Use PyErr_WarnEx instead. */ #undef PyErr_Warn int PyErr_Warn(PyObject *category, const char *text) { return PyErr_WarnEx(category, text, 1); } /* Warning with explicit origin */ int PyErr_WarnExplicitObject(PyObject *category, PyObject *message, PyObject *filename, int lineno, PyObject *module, PyObject *registry) { PyObject *res; if (category == NULL) category = PyExc_RuntimeWarning; res = warn_explicit(category, message, filename, lineno, module, registry, NULL, NULL); if (res == NULL) return -1; Py_DECREF(res); return 0; } int PyErr_WarnExplicit(PyObject *category, const char *text, const char *filename_str, int lineno, const char *module_str, PyObject *registry) { PyObject *message = PyUnicode_FromString(text); PyObject *filename = PyUnicode_DecodeFSDefault(filename_str); PyObject *module = NULL; int ret = -1; if (message == NULL || filename == NULL) goto exit; if (module_str != NULL) { module = PyUnicode_FromString(module_str); if (module == NULL) goto exit; } ret = PyErr_WarnExplicitObject(category, message, filename, lineno, module, registry); exit: Py_XDECREF(message); Py_XDECREF(module); Py_XDECREF(filename); return ret; } int PyErr_WarnExplicitFormat(PyObject *category, const char *filename_str, int lineno, const char *module_str, PyObject *registry, const char *format, ...) { PyObject *message; PyObject *module = NULL; PyObject *filename = PyUnicode_DecodeFSDefault(filename_str); int ret = -1; va_list vargs; if (filename == NULL) goto exit; if (module_str != NULL) { module = PyUnicode_FromString(module_str); if (module == NULL) goto exit; } #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, format); #else va_start(vargs); #endif message = PyUnicode_FromFormatV(format, vargs); if (message != NULL) { PyObject *res; res = warn_explicit(category, message, filename, lineno, module, registry, NULL, NULL); Py_DECREF(message); if (res != NULL) { Py_DECREF(res); ret = 0; } } va_end(vargs); exit: Py_XDECREF(module); Py_XDECREF(filename); return ret; } PyDoc_STRVAR(warn_doc, "Issue a warning, or maybe ignore it or raise an exception."); PyDoc_STRVAR(warn_explicit_doc, "Low-level inferface to warnings functionality."); static PyMethodDef warnings_functions[] = { {"warn", (PyCFunction)warnings_warn, METH_VARARGS | METH_KEYWORDS, warn_doc}, {"warn_explicit", (PyCFunction)warnings_warn_explicit, METH_VARARGS | METH_KEYWORDS, warn_explicit_doc}, {"_filters_mutated", (PyCFunction)warnings_filters_mutated, METH_NOARGS, NULL}, /* XXX(brett.cannon): add showwarning? */ /* XXX(brett.cannon): Reasonable to add formatwarning? */ {NULL, NULL} /* sentinel */ }; static PyObject * create_filter(PyObject *category, const char *action) { static PyObject *ignore_str = NULL; static PyObject *error_str = NULL; static PyObject *default_str = NULL; static PyObject *always_str = NULL; PyObject *action_obj = NULL; PyObject *lineno, *result; if (!strcmp(action, "ignore")) { if (ignore_str == NULL) { ignore_str = PyUnicode_InternFromString("ignore"); if (ignore_str == NULL) return NULL; } action_obj = ignore_str; } else if (!strcmp(action, "error")) { if (error_str == NULL) { error_str = PyUnicode_InternFromString("error"); if (error_str == NULL) return NULL; } action_obj = error_str; } else if (!strcmp(action, "default")) { if (default_str == NULL) { default_str = PyUnicode_InternFromString("default"); if (default_str == NULL) return NULL; } action_obj = default_str; } else if (!strcmp(action, "always")) { if (always_str == NULL) { always_str = PyUnicode_InternFromString("always"); if (always_str == NULL) return NULL; } action_obj = always_str; } else { Py_FatalError("unknown action"); } /* This assumes the line number is zero for now. */ lineno = PyLong_FromLong(0); if (lineno == NULL) return NULL; result = PyTuple_Pack(5, action_obj, Py_None, category, Py_None, lineno); Py_DECREF(lineno); return result; } static PyObject * init_filters(void) { PyObject *filters = PyList_New(5); unsigned int pos = 0; /* Post-incremented in each use. */ unsigned int x; const char *bytes_action, *resource_action; if (filters == NULL) return NULL; PyList_SET_ITEM(filters, pos++, create_filter(PyExc_DeprecationWarning, "ignore")); PyList_SET_ITEM(filters, pos++, create_filter(PyExc_PendingDeprecationWarning, "ignore")); PyList_SET_ITEM(filters, pos++, create_filter(PyExc_ImportWarning, "ignore")); if (Py_BytesWarningFlag > 1) bytes_action = "error"; else if (Py_BytesWarningFlag) bytes_action = "default"; else bytes_action = "ignore"; PyList_SET_ITEM(filters, pos++, create_filter(PyExc_BytesWarning, bytes_action)); /* resource usage warnings are enabled by default in pydebug mode */ #ifdef Py_DEBUG resource_action = "always"; #else resource_action = "ignore"; #endif PyList_SET_ITEM(filters, pos++, create_filter(PyExc_ResourceWarning, resource_action)); for (x = 0; x < pos; x += 1) { if (PyList_GET_ITEM(filters, x) == NULL) { Py_DECREF(filters); return NULL; } } return filters; } static struct PyModuleDef warningsmodule = { PyModuleDef_HEAD_INIT, MODULE_NAME, warnings__doc__, 0, warnings_functions, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC _PyWarnings_Init(void) { PyObject *m; m = PyModule_Create(&warningsmodule); if (m == NULL) return NULL; if (_filters == NULL) { _filters = init_filters(); if (_filters == NULL) return NULL; } Py_INCREF(_filters); if (PyModule_AddObject(m, "filters", _filters) < 0) return NULL; if (_once_registry == NULL) { _once_registry = PyDict_New(); if (_once_registry == NULL) return NULL; } Py_INCREF(_once_registry); if (PyModule_AddObject(m, "_onceregistry", _once_registry) < 0) return NULL; if (_default_action == NULL) { _default_action = PyUnicode_FromString("default"); if (_default_action == NULL) return NULL; } Py_INCREF(_default_action); if (PyModule_AddObject(m, "_defaultaction", _default_action) < 0) return NULL; _filters_version = 0; return m; }
38,307
1,323
jart/cosmopolitan
false