Commit 88aa3649 authored by Kevin Modzelewski's avatar Kevin Modzelewski

Merge pull request #356 from undingen/zipimport

Add the zipimport, csv and ssl module
parents e2115cba 012b3e89
...@@ -169,7 +169,7 @@ add_subdirectory(tools) ...@@ -169,7 +169,7 @@ add_subdirectory(tools)
add_executable(pyston $<TARGET_OBJECTS:PYSTON_MAIN_OBJECT> $<TARGET_OBJECTS:PYSTON_OBJECTS> $<TARGET_OBJECTS:FROM_CPYTHON>) add_executable(pyston $<TARGET_OBJECTS:PYSTON_MAIN_OBJECT> $<TARGET_OBJECTS:PYSTON_OBJECTS> $<TARGET_OBJECTS:FROM_CPYTHON>)
# Wrap the stdlib in --whole-archive to force all the symbols to be included and eventually exported # Wrap the stdlib in --whole-archive to force all the symbols to be included and eventually exported
target_link_libraries(pyston -Wl,--whole-archive stdlib -Wl,--no-whole-archive pthread m readline gmp unwind pypa double-conversion ${LLVM_LIBS} ${LIBLZMA_LIBRARIES} ${OPTIONAL_LIBRARIES}) target_link_libraries(pyston -Wl,--whole-archive stdlib -Wl,--no-whole-archive pthread m readline gmp ssl crypto unwind pypa double-conversion ${LLVM_LIBS} ${LIBLZMA_LIBRARIES} ${OPTIONAL_LIBRARIES})
# copy src/codegen/parse_ast.py to the build directory # copy src/codegen/parse_ast.py to the build directory
add_custom_command(TARGET pyston POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_SOURCE_DIR}/src/codegen/parse_ast.py ${CMAKE_BINARY_DIR}/src/codegen/parse_ast.py) add_custom_command(TARGET pyston POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_SOURCE_DIR}/src/codegen/parse_ast.py ${CMAKE_BINARY_DIR}/src/codegen/parse_ast.py)
......
...@@ -165,7 +165,7 @@ COMMON_CXXFLAGS += -DGITREV=$(shell git rev-parse HEAD | head -c 12) -DLLVMREV=$ ...@@ -165,7 +165,7 @@ COMMON_CXXFLAGS += -DGITREV=$(shell git rev-parse HEAD | head -c 12) -DLLVMREV=$
COMMON_CXXFLAGS += -DDEFAULT_PYTHON_MAJOR_VERSION=$(PYTHON_MAJOR_VERSION) -DDEFAULT_PYTHON_MINOR_VERSION=$(PYTHON_MINOR_VERSION) -DDEFAULT_PYTHON_MICRO_VERSION=$(PYTHON_MICRO_VERSION) COMMON_CXXFLAGS += -DDEFAULT_PYTHON_MAJOR_VERSION=$(PYTHON_MAJOR_VERSION) -DDEFAULT_PYTHON_MINOR_VERSION=$(PYTHON_MINOR_VERSION) -DDEFAULT_PYTHON_MICRO_VERSION=$(PYTHON_MICRO_VERSION)
# Use our "custom linker" that calls gold if available # Use our "custom linker" that calls gold if available
COMMON_LDFLAGS := -B$(TOOLS_DIR)/build_system -L/usr/local/lib -lpthread -lm -lunwind -llzma -L$(DEPS_DIR)/gcc-4.8.2-install/lib64 -lreadline -lgmp COMMON_LDFLAGS := -B$(TOOLS_DIR)/build_system -L/usr/local/lib -lpthread -lm -lunwind -llzma -L$(DEPS_DIR)/gcc-4.8.2-install/lib64 -lreadline -lgmp -lssl -lcrypto
COMMON_LDFLAGS += $(DEPS_DIR)/pypa-install/lib/libpypa.a COMMON_LDFLAGS += $(DEPS_DIR)/pypa-install/lib/libpypa.a
# Conditionally add libtinfo if available - otherwise nothing will be added # Conditionally add libtinfo if available - otherwise nothing will be added
...@@ -292,9 +292,9 @@ STDLIB_OBJS := stdlib.bc.o stdlib.stripped.bc.o ...@@ -292,9 +292,9 @@ STDLIB_OBJS := stdlib.bc.o stdlib.stripped.bc.o
STDLIB_RELEASE_OBJS := stdlib.release.bc.o STDLIB_RELEASE_OBJS := stdlib.release.bc.o
ASM_SRCS := $(wildcard src/runtime/*.S) ASM_SRCS := $(wildcard src/runtime/*.S)
STDMODULE_SRCS := errnomodule.c shamodule.c sha256module.c sha512module.c _math.c mathmodule.c md5.c md5module.c _randommodule.c _sre.c operator.c binascii.c pwdmodule.c posixmodule.c _struct.c datetimemodule.c _functoolsmodule.c _collectionsmodule.c itertoolsmodule.c resource.c signalmodule.c selectmodule.c fcntlmodule.c timemodule.c arraymodule.c zlibmodule.c _codecsmodule.c socketmodule.c unicodedata.c _weakref.c cStringIO.c _io/bufferedio.c _io/bytesio.c _io/fileio.c _io/iobase.c _io/_iomodule.c _io/stringio.c _io/textio.c $(EXTRA_STDMODULE_SRCS) STDMODULE_SRCS := errnomodule.c shamodule.c sha256module.c sha512module.c _math.c mathmodule.c md5.c md5module.c _randommodule.c _sre.c operator.c binascii.c pwdmodule.c posixmodule.c _struct.c datetimemodule.c _functoolsmodule.c _collectionsmodule.c itertoolsmodule.c resource.c signalmodule.c selectmodule.c fcntlmodule.c timemodule.c arraymodule.c zlibmodule.c _codecsmodule.c socketmodule.c unicodedata.c _weakref.c cStringIO.c _io/bufferedio.c _io/bytesio.c _io/fileio.c _io/iobase.c _io/_iomodule.c _io/stringio.c _io/textio.c zipimport.c _csv.c _ssl.c $(EXTRA_STDMODULE_SRCS)
STDOBJECT_SRCS := structseq.c capsule.c stringobject.c exceptions.c unicodeobject.c unicodectype.c bytearrayobject.c bytes_methods.c weakrefobject.c memoryobject.c iterobject.c $(EXTRA_STDOBJECT_SRCS) STDOBJECT_SRCS := structseq.c capsule.c stringobject.c exceptions.c unicodeobject.c unicodectype.c bytearrayobject.c bytes_methods.c weakrefobject.c memoryobject.c iterobject.c $(EXTRA_STDOBJECT_SRCS)
STDPYTHON_SRCS := pyctype.c getargs.c formatter_string.c pystrtod.c dtoa.c formatter_unicode.c structmember.c $(EXTRA_STDPYTHON_SRCS) STDPYTHON_SRCS := pyctype.c getargs.c formatter_string.c pystrtod.c dtoa.c formatter_unicode.c structmember.c marshal.c $(EXTRA_STDPYTHON_SRCS)
FROM_CPYTHON_SRCS := $(addprefix from_cpython/Modules/,$(STDMODULE_SRCS)) $(addprefix from_cpython/Objects/,$(STDOBJECT_SRCS)) $(addprefix from_cpython/Python/,$(STDPYTHON_SRCS)) FROM_CPYTHON_SRCS := $(addprefix from_cpython/Modules/,$(STDMODULE_SRCS)) $(addprefix from_cpython/Objects/,$(STDOBJECT_SRCS)) $(addprefix from_cpython/Python/,$(STDPYTHON_SRCS))
# The stdlib objects have slightly longer dependency chains, # The stdlib objects have slightly longer dependency chains,
......
...@@ -15,13 +15,13 @@ endforeach(STDLIB_FILE) ...@@ -15,13 +15,13 @@ endforeach(STDLIB_FILE)
add_custom_target(copy_stdlib ALL DEPENDS ${STDLIB_TARGETS}) add_custom_target(copy_stdlib ALL DEPENDS ${STDLIB_TARGETS})
# compile specified files in from_cpython/Modules # compile specified files in from_cpython/Modules
file(GLOB_RECURSE STDMODULE_SRCS Modules errnomodule.c shamodule.c sha256module.c sha512module.c _math.c mathmodule.c md5.c md5module.c _randommodule.c _sre.c operator.c binascii.c pwdmodule.c posixmodule.c _struct.c datetimemodule.c _functoolsmodule.c _collectionsmodule.c itertoolsmodule.c resource.c signalmodule.c selectmodule.c fcntlmodule.c timemodule.c arraymodule.c zlibmodule.c _codecsmodule.c socketmodule.c unicodedata.c _weakref.c cStringIO.c bufferedio.c bytesio.c fileio.c iobase.c _iomodule.c stringio.c textio.c) file(GLOB_RECURSE STDMODULE_SRCS Modules errnomodule.c shamodule.c sha256module.c sha512module.c _math.c mathmodule.c md5.c md5module.c _randommodule.c _sre.c operator.c binascii.c pwdmodule.c posixmodule.c _struct.c datetimemodule.c _functoolsmodule.c _collectionsmodule.c itertoolsmodule.c resource.c signalmodule.c selectmodule.c fcntlmodule.c timemodule.c arraymodule.c zlibmodule.c _codecsmodule.c socketmodule.c unicodedata.c _weakref.c cStringIO.c bufferedio.c bytesio.c fileio.c iobase.c _iomodule.c stringio.c textio.c zipimport.c _csv.c _ssl.c)
# compile specified files in from_cpython/Objects # compile specified files in from_cpython/Objects
file(GLOB_RECURSE STDOBJECT_SRCS Objects structseq.c capsule.c stringobject.c exceptions.c unicodeobject.c unicodectype.c bytearrayobject.c bytes_methods.c weakrefobject.c memoryobject.c iterobject.c) file(GLOB_RECURSE STDOBJECT_SRCS Objects structseq.c capsule.c stringobject.c exceptions.c unicodeobject.c unicodectype.c bytearrayobject.c bytes_methods.c weakrefobject.c memoryobject.c iterobject.c)
# compile specified files in from_cpython/Python # compile specified files in from_cpython/Python
file(GLOB_RECURSE STDPYTHON_SRCS Python getargs.c pyctype.c formatter_string.c pystrtod.c dtoa.c formatter_unicode.c structmember.c) file(GLOB_RECURSE STDPYTHON_SRCS Python getargs.c pyctype.c formatter_string.c pystrtod.c dtoa.c formatter_unicode.c structmember.c marshal.c)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-missing-field-initializers -Wno-tautological-compare -Wno-type-limits -Wno-unused-result -Wno-strict-aliasing") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-missing-field-initializers -Wno-tautological-compare -Wno-type-limits -Wno-unused-result -Wno-strict-aliasing")
add_library(FROM_CPYTHON OBJECT ${STDMODULE_SRCS} ${STDOBJECT_SRCS} ${STDPYTHON_SRCS}) add_library(FROM_CPYTHON OBJECT ${STDMODULE_SRCS} ${STDOBJECT_SRCS} ${STDPYTHON_SRCS})
// This file is originally from CPython 2.7, with modifications for Pyston
/* Interface for marshal.c */
#ifndef Py_MARSHAL_H
#define Py_MARSHAL_H
#ifdef __cplusplus
extern "C" {
#endif
#define Py_MARSHAL_VERSION 2
PyAPI_FUNC(void) PyMarshal_WriteLongToFile(long, FILE *, int) PYSTON_NOEXCEPT;
PyAPI_FUNC(void) PyMarshal_WriteObjectToFile(PyObject *, FILE *, int) PYSTON_NOEXCEPT;
PyAPI_FUNC(PyObject *) PyMarshal_WriteObjectToString(PyObject *, int) PYSTON_NOEXCEPT;
PyAPI_FUNC(long) PyMarshal_ReadLongFromFile(FILE *) PYSTON_NOEXCEPT;
PyAPI_FUNC(int) PyMarshal_ReadShortFromFile(FILE *) PYSTON_NOEXCEPT;
PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromFile(FILE *) PYSTON_NOEXCEPT;
PyAPI_FUNC(PyObject *) PyMarshal_ReadLastObjectFromFile(FILE *) PYSTON_NOEXCEPT;
PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromString(char *, Py_ssize_t) PYSTON_NOEXCEPT;
#ifdef __cplusplus
}
#endif
#endif /* !Py_MARSHAL_H */
...@@ -39,7 +39,9 @@ def _complain_ifclosed(closed): ...@@ -39,7 +39,9 @@ def _complain_ifclosed(closed):
if closed: if closed:
raise ValueError, "I/O operation on closed file" raise ValueError, "I/O operation on closed file"
class StringIO: # Pyston change: make this a new style class, looks like we don't support iterating otherwise
# class StringIO:
class StringIO(object):
"""class StringIO([buffer]) """class StringIO([buffer])
When a StringIO object is created, it can be initialized to an existing When a StringIO object is created, it can be initialized to an existing
......
...@@ -69,8 +69,9 @@ class excel_tab(excel): ...@@ -69,8 +69,9 @@ class excel_tab(excel):
delimiter = '\t' delimiter = '\t'
register_dialect("excel-tab", excel_tab) register_dialect("excel-tab", excel_tab)
# Pyston change: make this a new style class, looks like we don't support iterating otherwise
class DictReader: # class DictReader:
class DictReader(object):
def __init__(self, f, fieldnames=None, restkey=None, restval=None, def __init__(self, f, fieldnames=None, restkey=None, restval=None,
dialect="excel", *args, **kwds): dialect="excel", *args, **kwds):
self._fieldnames = fieldnames # list of keys for the dict self._fieldnames = fieldnames # list of keys for the dict
......
...@@ -19,7 +19,8 @@ ...@@ -19,7 +19,8 @@
#ifdef WITH_THREAD #ifdef WITH_THREAD
#include "pythread.h" #include "pythread.h"
// Pyston change: changed to use our internal API
/*
#define PySSL_BEGIN_ALLOW_THREADS { \ #define PySSL_BEGIN_ALLOW_THREADS { \
PyThreadState *_save = NULL; \ PyThreadState *_save = NULL; \
if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} if (_ssl_locks_count>0) {_save = PyEval_SaveThread();}
...@@ -27,6 +28,13 @@ ...@@ -27,6 +28,13 @@
#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; #define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()};
#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ #define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \
} }
*/
#define PySSL_BEGIN_ALLOW_THREADS { \
if (_ssl_locks_count>0) beginAllowThreads();
#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0) endAllowThreads();
#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0) beginAllowThreads();
#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0) endAllowThreads(); \
}
#else /* no WITH_THREAD */ #else /* no WITH_THREAD */
...@@ -1745,6 +1753,9 @@ init_ssl(void) ...@@ -1745,6 +1753,9 @@ init_ssl(void)
Py_TYPE(&PySSL_Type) = &PyType_Type; Py_TYPE(&PySSL_Type) = &PyType_Type;
// Pyston change
PyType_Ready(&PySSL_Type);
m = Py_InitModule3("_ssl", PySSL_methods, module_doc); m = Py_InitModule3("_ssl", PySSL_methods, module_doc);
if (m == NULL) if (m == NULL)
return; return;
......
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
#include "marshal.h" #include "marshal.h"
#include <time.h> #include <time.h>
// Pyston change:
#include <sys/stat.h>
#define IS_SOURCE 0x0 #define IS_SOURCE 0x0
#define IS_BYTECODE 0x1 #define IS_BYTECODE 0x1
...@@ -46,10 +48,10 @@ static PyObject *zip_directory_cache = NULL; ...@@ -46,10 +48,10 @@ static PyObject *zip_directory_cache = NULL;
/* forward decls */ /* forward decls */
static PyObject *read_directory(char *archive); static PyObject *read_directory(char *archive);
static PyObject *get_data(char *archive, PyObject *toc_entry); static PyObject *get_data(char *archive, PyObject *toc_entry);
static PyObject *get_module_code(ZipImporter *self, char *fullname, static PyObject *get_module_code(ZipImporter *self, char *fullname,
int *p_ispackage, char **p_modpath); int *p_ispackage, char **p_modpath);
#define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type) #define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type)
...@@ -956,6 +958,8 @@ eq_mtime(time_t t1, time_t t2) ...@@ -956,6 +958,8 @@ eq_mtime(time_t t1, time_t t2)
return d <= 1; return d <= 1;
} }
// Pyston change: We don't support bytecode archives yet
#if 0
/* Given the contents of a .py[co] file in a buffer, unmarshal the data /* Given the contents of a .py[co] file in a buffer, unmarshal the data
and return the code object. Return None if it the magic word doesn't and return the code object. Return None if it the magic word doesn't
match (we do this instead of raising an exception as we fall back match (we do this instead of raising an exception as we fall back
...@@ -1103,6 +1107,7 @@ get_mtime_of_source(ZipImporter *self, char *path) ...@@ -1103,6 +1107,7 @@ get_mtime_of_source(ZipImporter *self, char *path)
path[lastchar] = savechar; path[lastchar] = savechar;
return mtime; return mtime;
} }
#endif // Pyston change
/* Return the code object for the module named by 'fullname' from the /* Return the code object for the module named by 'fullname' from the
Zip archive as a new reference. */ Zip archive as a new reference. */
...@@ -1123,6 +1128,11 @@ get_code_from_data(ZipImporter *self, int ispackage, int isbytecode, ...@@ -1123,6 +1128,11 @@ get_code_from_data(ZipImporter *self, int ispackage, int isbytecode,
modpath = PyString_AsString(PyTuple_GetItem(toc_entry, 0)); modpath = PyString_AsString(PyTuple_GetItem(toc_entry, 0));
// Pyston change: Just return the source code for now
#if 1
assert(!isbytecode);
return data;
#else // Pyston change
if (isbytecode) { if (isbytecode) {
code = unmarshal_code(modpath, data, mtime); code = unmarshal_code(modpath, data, mtime);
} }
...@@ -1131,6 +1141,7 @@ get_code_from_data(ZipImporter *self, int ispackage, int isbytecode, ...@@ -1131,6 +1141,7 @@ get_code_from_data(ZipImporter *self, int ispackage, int isbytecode,
} }
Py_DECREF(data); Py_DECREF(data);
return code; return code;
#endif // Pyston change
} }
/* Get the code object associated with the module specified by /* Get the code object associated with the module specified by
...@@ -1164,8 +1175,14 @@ get_module_code(ZipImporter *self, char *fullname, ...@@ -1164,8 +1175,14 @@ get_module_code(ZipImporter *self, char *fullname,
int ispackage = zso->type & IS_PACKAGE; int ispackage = zso->type & IS_PACKAGE;
int isbytecode = zso->type & IS_BYTECODE; int isbytecode = zso->type & IS_BYTECODE;
if (isbytecode)
mtime = get_mtime_of_source(self, path); if (isbytecode) {
// Pyston change: We don't support bytecode archives currently
// mtime = get_mtime_of_source(self, path);
PyErr_Format(ZipImportError, "Pyston can't load bytecode from archives yet. ' '%.200s'", fullname);
return NULL;
}
if (p_ispackage != NULL) if (p_ispackage != NULL)
*p_ispackage = ispackage; *p_ispackage = ispackage;
code = get_code_from_data(self, ispackage, code = get_code_from_data(self, ispackage,
...@@ -1254,4 +1271,8 @@ initzipimport(void) ...@@ -1254,4 +1271,8 @@ initzipimport(void)
if (PyModule_AddObject(mod, "_zip_directory_cache", if (PyModule_AddObject(mod, "_zip_directory_cache",
zip_directory_cache) < 0) zip_directory_cache) < 0)
return; return;
// Pyston change: register zip module import hook
PyObject* zipimporter = PyObject_GetAttrString(mod, "zipimporter");
PyList_Append(PySys_GetObject("path_hooks"), zipimporter);
} }
...@@ -196,9 +196,6 @@ PyCapsule_SetContext(PyObject *o, void *context) ...@@ -196,9 +196,6 @@ PyCapsule_SetContext(PyObject *o, void *context)
void * void *
PyCapsule_Import(const char *name, int no_block) PyCapsule_Import(const char *name, int no_block)
{ {
// Pyston change:
Py_FatalError("Pyston TODO: implement this");
#if 0
PyObject *object = NULL; PyObject *object = NULL;
void *return_value = NULL; void *return_value = NULL;
char *trace; char *trace;
...@@ -255,7 +252,6 @@ EXIT: ...@@ -255,7 +252,6 @@ EXIT:
PyMem_FREE(name_dup); PyMem_FREE(name_dup);
} }
return return_value; return return_value;
#endif
} }
......
This diff is collapsed.
...@@ -107,6 +107,15 @@ static PyObject* do_mkvalue(const char** p_format, va_list* p_va, int flags) noe ...@@ -107,6 +107,15 @@ static PyObject* do_mkvalue(const char** p_format, va_list* p_va, int flags) noe
case 'H': case 'H':
return PyInt_FromLong((long)va_arg(*p_va, unsigned int)); return PyInt_FromLong((long)va_arg(*p_va, unsigned int));
case 'I': {
unsigned int n;
n = va_arg(*p_va, unsigned int);
if (n > (unsigned long)PyInt_GetMax())
return PyLong_FromUnsignedLong((unsigned long)n);
else
return PyInt_FromLong(n);
}
case 'n': case 'n':
#if SIZEOF_SIZE_T != SIZEOF_LONG #if SIZEOF_SIZE_T != SIZEOF_LONG
return PyInt_FromSsize_t(va_arg(*p_va, Py_ssize_t)); return PyInt_FromSsize_t(va_arg(*p_va, Py_ssize_t));
......
...@@ -461,8 +461,8 @@ PythonFrameIterator::Manager unwindPythonFrames() { ...@@ -461,8 +461,8 @@ PythonFrameIterator::Manager unwindPythonFrames() {
static std::unique_ptr<PythonFrameIterator> getTopPythonFrame() { static std::unique_ptr<PythonFrameIterator> getTopPythonFrame() {
std::unique_ptr<PythonFrameIterator> fr = PythonFrameIterator::begin(); std::unique_ptr<PythonFrameIterator> fr = PythonFrameIterator::begin();
RELEASE_ASSERT(fr != PythonFrameIterator::end(), "no valid python frames??"); if (fr == PythonFrameIterator::end())
return std::unique_ptr<PythonFrameIterator>();
return fr; return fr;
} }
...@@ -533,12 +533,16 @@ ExcInfo* getFrameExcInfo() { ...@@ -533,12 +533,16 @@ ExcInfo* getFrameExcInfo() {
} }
CompiledFunction* getTopCompiledFunction() { CompiledFunction* getTopCompiledFunction() {
auto rtn = getTopPythonFrame();
if (!rtn)
return NULL;
return getTopPythonFrame()->getCF(); return getTopPythonFrame()->getCF();
} }
BoxedModule* getCurrentModule() { BoxedModule* getCurrentModule() {
CompiledFunction* compiledFunction = getTopCompiledFunction(); CompiledFunction* compiledFunction = getTopCompiledFunction();
assert(compiledFunction); if (!compiledFunction)
return NULL;
return compiledFunction->clfunc->source->parent_module; return compiledFunction->clfunc->source->parent_module;
} }
......
...@@ -75,5 +75,7 @@ bool BOOLS_AS_I64 = ENABLE_FRAME_INTROSPECTION; ...@@ -75,5 +75,7 @@ bool BOOLS_AS_I64 = ENABLE_FRAME_INTROSPECTION;
extern "C" { extern "C" {
int Py_IgnoreEnvironmentFlag = 1; int Py_IgnoreEnvironmentFlag = 1;
int Py_OptimizeFlag = 0;
int Py_VerboseFlag = 0;
} }
} }
...@@ -275,6 +275,8 @@ void setupSys() { ...@@ -275,6 +275,8 @@ void setupSys() {
"getfilesystemencoding")); "getfilesystemencoding"));
sys_module->giveAttr("meta_path", new BoxedList()); sys_module->giveAttr("meta_path", new BoxedList());
sys_module->giveAttr("path_hooks", new BoxedList());
sys_module->giveAttr("path_importer_cache", new BoxedDict());
// TODO: should configure this in a better way // TODO: should configure this in a better way
sys_module->giveAttr("prefix", boxStrConstant("/usr")); sys_module->giveAttr("prefix", boxStrConstant("/usr"));
......
...@@ -801,7 +801,11 @@ error: ...@@ -801,7 +801,11 @@ error:
} }
Box* fileIterNext(BoxedFile* s) { Box* fileIterNext(BoxedFile* s) {
return fileReadline1(s); Box* rtn = fileReadline1(s);
assert(!rtn || rtn->cls == str_cls);
if (!rtn || ((BoxedString*)rtn)->s.empty())
raiseExcHelper(StopIteration, "");
return rtn;
} }
bool fileEof(BoxedFile* self) { bool fileEof(BoxedFile* self) {
......
...@@ -30,6 +30,7 @@ static const std::string all_str("__all__"); ...@@ -30,6 +30,7 @@ static const std::string all_str("__all__");
static const std::string name_str("__name__"); static const std::string name_str("__name__");
static const std::string path_str("__path__"); static const std::string path_str("__path__");
static const std::string package_str("__package__"); static const std::string package_str("__package__");
static BoxedClass* null_importer_cls;
BoxedModule* createAndRunModule(const std::string& name, const std::string& fn) { BoxedModule* createAndRunModule(const std::string& name, const std::string& fn) {
BoxedModule* module = createModule(name, fn); BoxedModule* module = createModule(name, fn);
...@@ -71,6 +72,65 @@ static bool pathExists(const std::string& path) { ...@@ -71,6 +72,65 @@ static bool pathExists(const std::string& path) {
return exists; return exists;
} }
/* Return an importer object for a sys.path/pkg.__path__ item 'p',
possibly by fetching it from the path_importer_cache dict. If it
wasn't yet cached, traverse path_hooks until a hook is found
that can handle the path item. Return None if no hook could;
this tells our caller it should fall back to the builtin
import mechanism. Cache the result in path_importer_cache.
Returns a borrowed reference. */
extern "C" PyObject* get_path_importer(PyObject* path_importer_cache, PyObject* path_hooks, PyObject* p) noexcept {
PyObject* importer;
Py_ssize_t j, nhooks;
/* These conditions are the caller's responsibility: */
assert(PyList_Check(path_hooks));
assert(PyDict_Check(path_importer_cache));
nhooks = PyList_Size(path_hooks);
if (nhooks < 0)
return NULL; /* Shouldn't happen */
importer = PyDict_GetItem(path_importer_cache, p);
if (importer != NULL)
return importer;
/* set path_importer_cache[p] to None to avoid recursion */
if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
return NULL;
for (j = 0; j < nhooks; j++) {
PyObject* hook = PyList_GetItem(path_hooks, j);
if (hook == NULL)
return NULL;
importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
if (importer != NULL)
break;
if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
return NULL;
}
PyErr_Clear();
}
if (importer == NULL) {
importer = PyObject_CallFunctionObjArgs(null_importer_cls, p, NULL);
if (importer == NULL) {
if (PyErr_ExceptionMatches(PyExc_ImportError)) {
PyErr_Clear();
return Py_None;
}
}
}
if (importer != NULL) {
int err = PyDict_SetItem(path_importer_cache, p, importer);
Py_DECREF(importer);
if (err != 0)
return NULL;
}
return importer;
}
struct SearchResult { struct SearchResult {
// Each of these fields are only valid/used for certain filetypes: // Each of these fields are only valid/used for certain filetypes:
std::string path; std::string path;
...@@ -119,6 +179,14 @@ SearchResult findModule(const std::string& name, const std::string& full_name, B ...@@ -119,6 +179,14 @@ SearchResult findModule(const std::string& name, const std::string& full_name, B
raiseExcHelper(RuntimeError, "sys.path must be a list of directory names"); raiseExcHelper(RuntimeError, "sys.path must be a list of directory names");
} }
BoxedList* path_hooks = static_cast<BoxedList*>(sys_module->getattr("path_hooks"));
if (!path_hooks || path_hooks->cls != list_cls)
raiseExcHelper(RuntimeError, "sys.path_hooks must be a list of import hooks");
BoxedDict* path_importer_cache = static_cast<BoxedDict*>(sys_module->getattr("path_importer_cache"));
if (!path_importer_cache || path_importer_cache->cls != dict_cls)
raiseExcHelper(RuntimeError, "sys.path_importer_cache must be a dict");
llvm::SmallString<128> joined_path; llvm::SmallString<128> joined_path;
for (int i = 0; i < path_list->size; i++) { for (int i = 0; i < path_list->size; i++) {
Box* _p = path_list->elts->elts[i]; Box* _p = path_list->elts->elts[i];
...@@ -133,6 +201,19 @@ SearchResult findModule(const std::string& name, const std::string& full_name, B ...@@ -133,6 +201,19 @@ SearchResult findModule(const std::string& name, const std::string& full_name, B
llvm::sys::path::append(joined_path, "__init__.py"); llvm::sys::path::append(joined_path, "__init__.py");
std::string fn(joined_path.str()); std::string fn(joined_path.str());
PyObject* importer = get_path_importer(path_importer_cache, path_hooks, _p);
if (importer == NULL)
return SearchResult("", SearchResult::SEARCH_ERROR);
if (importer != None) {
auto path_pass = path_list ? path_list : None;
Box* loader = callattr(importer, &find_module_str,
CallattrFlags({.cls_only = false, .null_on_nonexistent = false }), ArgPassSpec(2),
new BoxedString(full_name), path_pass, NULL, NULL, NULL);
if (loader != None)
return SearchResult(loader);
}
if (pathExists(fn)) if (pathExists(fn))
return SearchResult(std::move(dn), SearchResult::PKG_DIRECTORY); return SearchResult(std::move(dn), SearchResult::PKG_DIRECTORY);
...@@ -416,7 +497,7 @@ extern "C" void _PyImport_ReInitLock() noexcept { ...@@ -416,7 +497,7 @@ extern "C" void _PyImport_ReInitLock() noexcept {
} }
extern "C" PyObject* PyImport_ImportModuleNoBlock(const char* name) noexcept { extern "C" PyObject* PyImport_ImportModuleNoBlock(const char* name) noexcept {
Py_FatalError("unimplemented"); return PyImport_ImportModule(name);
} }
// This function has the same behaviour as __import__() // This function has the same behaviour as __import__()
...@@ -476,6 +557,70 @@ extern "C" PyObject* PyImport_ImportModule(const char* name) noexcept { ...@@ -476,6 +557,70 @@ extern "C" PyObject* PyImport_ImportModule(const char* name) noexcept {
} }
} }
/* Get the module object corresponding to a module name.
First check the modules dictionary if there's one there,
if not, create a new one and insert it in the modules dictionary.
Because the former action is most common, THIS DOES NOT RETURN A
'NEW' REFERENCE! */
extern "C" PyObject* PyImport_AddModule(const char* name) noexcept {
try {
PyObject* modules = getSysModulesDict();
PyObject* m = PyDict_GetItemString(modules, name);
if (m != NULL && m->cls == module_cls)
return m;
return createModule(name, name);
} catch (ExcInfo e) {
setCAPIException(e);
return NULL;
}
}
extern "C" PyObject* PyImport_ExecCodeModuleEx(char* name, PyObject* co, char* pathname) noexcept {
try {
RELEASE_ASSERT(co->cls == str_cls, "");
BoxedString* code = (BoxedString*)co;
BoxedModule* module = (BoxedModule*)PyImport_AddModule(name);
if (module == NULL)
return NULL;
AST_Module* ast = parse_string(code->s.c_str());
compileAndRunModule(ast, module);
module->setattr("__file__", boxString(pathname), NULL);
return module;
} catch (ExcInfo e) {
setCAPIException(e);
return NULL;
}
}
static int isdir(const char* path) {
struct stat statbuf;
return stat(path, &statbuf) == 0 && S_ISDIR(statbuf.st_mode);
}
Box* nullImporterInit(Box* self, Box* _path) {
RELEASE_ASSERT(self->cls == null_importer_cls, "");
if (_path->cls != str_cls)
raiseExcHelper(TypeError, "must be string, not %s", getTypeName(_path));
BoxedString* path = (BoxedString*)_path;
if (path->s.empty())
raiseExcHelper(ImportError, "empty pathname");
if (isdir(path->s.c_str()))
raiseExcHelper(ImportError, "existing directory");
return None;
}
Box* nullImporterFindModule(Box* self, Box* fullname, Box* path) {
return None;
}
extern "C" Box* import(int level, Box* from_imports, const std::string* module_name) { extern "C" Box* import(int level, Box* from_imports, const std::string* module_name) {
std::string _module_name(*module_name); std::string _module_name(*module_name);
return importModuleLevel(&_module_name, getCurrentModule(), from_imports, level); return importModuleLevel(&_module_name, getCurrentModule(), from_imports, level);
...@@ -548,6 +693,16 @@ void setupImport() { ...@@ -548,6 +693,16 @@ void setupImport() {
imp_module->giveAttr("C_BUILTIN", boxInt(SearchResult::C_BUILTIN)); imp_module->giveAttr("C_BUILTIN", boxInt(SearchResult::C_BUILTIN));
imp_module->giveAttr("PY_FROZEN", boxInt(SearchResult::PY_FROZEN)); imp_module->giveAttr("PY_FROZEN", boxInt(SearchResult::PY_FROZEN));
null_importer_cls = BoxedHeapClass::create(type_cls, object_cls, NULL, 0, 0, sizeof(Box), false, "NullImporter");
null_importer_cls->giveAttr(
"__init__", new BoxedFunction(boxRTFunction((void*)nullImporterInit, NONE, 2, 1, false, false), { None }));
null_importer_cls->giveAttr(
"find_module",
new BoxedBuiltinFunctionOrMethod(boxRTFunction((void*)nullImporterFindModule, NONE, 2, 1, false, false),
"find_module", { None }));
null_importer_cls->freeze();
imp_module->giveAttr("NullImporter", null_importer_cls);
CLFunction* find_module_func CLFunction* find_module_func
= boxRTFunction((void*)impFindModule, UNKNOWN, 2, 1, false, false, ParamNames({ "name", "path" }, "", "")); = boxRTFunction((void*)impFindModule, UNKNOWN, 2, 1, false, false, ParamNames({ "name", "path" }, "", ""));
imp_module->giveAttr("find_module", new BoxedBuiltinFunctionOrMethod(find_module_func, "find_module", { None })); imp_module->giveAttr("find_module", new BoxedBuiltinFunctionOrMethod(find_module_func, "find_module", { None }));
......
...@@ -32,6 +32,10 @@ ...@@ -32,6 +32,10 @@
namespace pyston { namespace pyston {
extern "C" long PyInt_GetMax() noexcept {
return LONG_MAX; /* To initialize sys.maxint */
}
extern "C" unsigned long PyInt_AsUnsignedLongMask(PyObject* op) noexcept { extern "C" unsigned long PyInt_AsUnsignedLongMask(PyObject* op) noexcept {
if (op && PyInt_Check(op)) if (op && PyInt_Check(op))
return PyInt_AS_LONG((PyIntObject*)op); return PyInt_AS_LONG((PyIntObject*)op);
......
...@@ -317,6 +317,10 @@ extern "C" PyObject* PyString_InternFromString(const char* s) noexcept { ...@@ -317,6 +317,10 @@ extern "C" PyObject* PyString_InternFromString(const char* s) noexcept {
return new BoxedString(s); return new BoxedString(s);
} }
extern "C" void PyString_InternInPlace(PyObject**) noexcept {
Py_FatalError("unimplemented");
}
/* Format codes /* Format codes
* F_LJUST '-' * F_LJUST '-'
* F_SIGN '+' * F_SIGN '+'
......
...@@ -70,6 +70,9 @@ extern "C" void initunicodedata(); ...@@ -70,6 +70,9 @@ extern "C" void initunicodedata();
extern "C" void init_weakref(); extern "C" void init_weakref();
extern "C" void initcStringIO(); extern "C" void initcStringIO();
extern "C" void init_io(); extern "C" void init_io();
extern "C" void initzipimport();
extern "C" void init_csv();
extern "C" void init_ssl();
namespace pyston { namespace pyston {
...@@ -1516,6 +1519,7 @@ void setupRuntime() { ...@@ -1516,6 +1519,7 @@ void setupRuntime() {
setupImport(); setupImport();
setupPyston(); setupPyston();
PyType_Ready(&PyByteArrayIter_Type);
PyType_Ready(&PyCapsule_Type); PyType_Ready(&PyCapsule_Type);
PyType_Ready(&PyCallIter_Type); PyType_Ready(&PyCallIter_Type);
...@@ -1549,6 +1553,9 @@ void setupRuntime() { ...@@ -1549,6 +1553,9 @@ void setupRuntime() {
init_weakref(); init_weakref();
initcStringIO(); initcStringIO();
init_io(); init_io();
initzipimport();
init_csv();
init_ssl();
// some additional setup to ensure weakrefs participate in our GC // some additional setup to ensure weakrefs participate in our GC
BoxedClass* weakref_ref_cls = &_PyWeakref_RefType; BoxedClass* weakref_ref_cls = &_PyWeakref_RefType;
......
import csv
import StringIO
csvfile = StringIO.StringIO()
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})
csvfile.seek(0)
print csvfile.getvalue()
reader = csv.DictReader(csvfile)
for row in reader:
print row['first_name'], row['last_name']
...@@ -4,3 +4,12 @@ e = imp.find_module("encodings") ...@@ -4,3 +4,12 @@ e = imp.find_module("encodings")
print e[0] print e[0]
m = imp.load_module("myenc", e[0], e[1], e[2]) m = imp.load_module("myenc", e[0], e[1], e[2])
print m.__name__ print m.__name__
# Null Importer tests
for a in (1, "", "/proc", "nonexisting_dir"):
try:
i = imp.NullImporter(a)
print i.find_module("foo")
except Exception as e:
print e
import ssl
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s)
if 0:
ssl_sock.connect(("google.com", 443))
print ssl_sock.getpeercert()
ssl_sock.write("GET / \n")
print ssl_sock.read()
print ssl_sock.getsockname()
ssl_sock.close()
import sys, os
# this zip contains two pkgs: test1 and test2
zipdir = os.path.dirname(os.path.realpath(__file__))
filename = zipdir + "/zipimport_test_file.zip"
sys.path.append(filename)
import test1
import test2
import os
import zipimport
# this zip contains two pkgs: test1 and test2
zipdir = os.path.dirname(os.path.realpath(__file__))
filename = zipdir + "/zipimport_test_file.zip"
z = zipimport.zipimporter(filename)
for name in ("test1", "test2", "test3"):
try:
z.is_package(name)
print z.archive
print z.prefix
m = z.load_module(name)
print m.__file__
print m.__name__
except Exception as e:
print e
...@@ -9,7 +9,7 @@ add_custom_target(unittests) ...@@ -9,7 +9,7 @@ add_custom_target(unittests)
macro(add_unittest unittest) macro(add_unittest unittest)
add_executable(${unittest}_unittest EXCLUDE_FROM_ALL ${unittest}.cpp $<TARGET_OBJECTS:PYSTON_OBJECTS> $<TARGET_OBJECTS:FROM_CPYTHON>) add_executable(${unittest}_unittest EXCLUDE_FROM_ALL ${unittest}.cpp $<TARGET_OBJECTS:PYSTON_OBJECTS> $<TARGET_OBJECTS:FROM_CPYTHON>)
target_link_libraries(${unittest}_unittest stdlib gmp readline pypa double-conversion unwind gtest gtest_main ${LLVM_LIBS} ${LIBLZMA_LIBRARIES}) target_link_libraries(${unittest}_unittest stdlib gmp ssl crypto readline pypa double-conversion unwind gtest gtest_main ${LLVM_LIBS} ${LIBLZMA_LIBRARIES})
add_dependencies(${unittest}_unittest gtest gtest_main) add_dependencies(${unittest}_unittest gtest gtest_main)
add_dependencies(unittests ${unittest}_unittest) add_dependencies(unittests ${unittest}_unittest)
endmacro() endmacro()
......
...@@ -9,5 +9,5 @@ add_dependencies(publicize ${LLVM_LIBS_EXTRA}) ...@@ -9,5 +9,5 @@ add_dependencies(publicize ${LLVM_LIBS_EXTRA})
include_directories(${CMAKE_SOURCE_DIR}/src) include_directories(${CMAKE_SOURCE_DIR}/src)
add_executable(astprint EXCLUDE_FROM_ALL astprint.cpp $<TARGET_OBJECTS:PYSTON_OBJECTS> $<TARGET_OBJECTS:FROM_CPYTHON>) add_executable(astprint EXCLUDE_FROM_ALL astprint.cpp $<TARGET_OBJECTS:PYSTON_OBJECTS> $<TARGET_OBJECTS:FROM_CPYTHON>)
target_link_libraries(astprint stdlib gmp readline pypa double-conversion unwind ${LLVM_LIBS} ${LIBLZMA_LIBRARIES}) target_link_libraries(astprint stdlib gmp ssl crypto readline pypa double-conversion unwind ${LLVM_LIBS} ${LIBLZMA_LIBRARIES})
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment