static Box* createAndRunModule(BoxedString* name, const std::string& fn, const std::string& module_path) { BoxedModule* module = createModule(name, fn.c_str()); Box* b_path = boxString(module_path); BoxedList* path_list = new BoxedList(); listAppendInternal(path_list, b_path); static BoxedString* path_str = internStringImmortal("__path__"); module->setattr(path_str, path_list, NULL); AST_Module* ast = caching_parse_file(fn.c_str(), /* future_flags = */ 0); assert(ast); try { compileAndRunModule(ast, module); } catch (ExcInfo e) { removeModule(name); throw e; } Box* r = getSysModulesDict()->getOrNull(name); if (!r) raiseExcHelper(ImportError, "Loaded module %.200s not found in sys.modules", name->c_str()); return r; }
BoxedModule* createAndRunModule(const std::string& name, const std::string& fn) { BoxedModule* module = createModule(name, fn); AST_Module* ast = caching_parse(fn.c_str()); compileAndRunModule(ast, module); return module; }
void ParticleEmitter::deserialize(InputBlob& blob, ResourceManager& manager, bool has_version) { int version = (int)ParticleEmitterVersion::INVALID; if (has_version) { blob.read(version); if (version > (int)ParticleEmitterVersion::SPAWN_COUNT) blob.read(m_spawn_count); } blob.read(m_spawn_period); blob.read(m_initial_life); blob.read(m_initial_size); blob.read(m_entity); char path[MAX_PATH_LENGTH]; blob.readString(path, lengthOf(path)); auto material_manager = manager.get(ResourceManager::MATERIAL); auto material = static_cast<Material*>(material_manager->load(Lumix::Path(path))); setMaterial(material); int size; blob.read(size); for (auto* module : m_modules) { LUMIX_DELETE(m_allocator, module); } m_modules.clear(); for (int i = 0; i < size; ++i) { uint32 type; blob.read(type); auto* module = createModule(type, *this); m_modules.push(module); module->deserialize(blob, version); } }
void ParticleEmitter::deserialize(InputBlob& blob, ResourceManager& manager) { blob.read(m_spawn_count); blob.read(m_spawn_period); blob.read(m_initial_life); blob.read(m_initial_size); blob.read(m_entity); blob.read(m_autoemit); blob.read(m_local_space); char path[MAX_PATH_LENGTH]; blob.readString(path, lengthOf(path)); auto material_manager = manager.get(MATERIAL_TYPE); auto material = static_cast<Material*>(material_manager->load(Path(path))); setMaterial(material); int size; blob.read(size); for (auto* module : m_modules) { LUMIX_DELETE(m_allocator, module); } m_modules.clear(); for (int i = 0; i < size; ++i) { ParticleEmitter::ModuleBase* module = nullptr; u32 hash; blob.read(hash); ComponentType type = PropertyRegister::getComponentTypeFromHash(hash); module = createModule(type, *this); if (module) { m_modules.push(module); } } }
void setupMath() { math_module = createModule("math", "__builtin__"); math_module->giveAttr("pi", boxFloat(M_PI)); _addFunc("sqrt", (void*)mathSqrtInt, (void*)mathSqrtFloat, (void*)mathSqrt); _addFunc("tan", (void*)mathTanInt, (void*)mathTanFloat, (void*)mathSqrt); }
/* ** External API function used to create a new virtual-table module. */ int sqlite3_create_module( sqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ const sqlite3_module *pModule, /* The definition of the module */ void *pAux /* Context pointer for xCreate/xConnect */ ){ return createModule(db, zName, pModule, pAux, 0); }
// static void ICommandLineOptionsModule::registerModuleDirect( CommandLineModuleManager *manager, const char *name, const char *description, ICommandLineOptionsModulePointer module) { CommandLineModulePointer wrapperModule( createModule(name, description, std::move(module))); manager->addModule(std::move(wrapperModule)); }
// Initialises the pipeline, creating required modules and data blobs, // and requesting remote data. void SignalProcessingPipeline::init() { // Create the pipeline modules and any local data blobs. amplifier = (SignalAmplifier*) createModule("SignalAmplifier"); outputData = (SignalData*) createBlob("SignalData"); // Request remote data. requestRemoteData("SignalData"); }
/** * @details * Initialises the pipeline. * * This method is run once on construction of the pipeline. */ void TimingPipeline::init() { // Create modules ppfChanneliser = (PPFChanneliser *) createModule("PPFChanneliser"); stokesGenerator = (StokesGenerator *) createModule("StokesGenerator"); rfiClipper = (RFI_Clipper *) createModule("RFI_Clipper"); stokesIntegrator = (StokesIntegrator *) createModule("StokesIntegrator"); weightedIntStokes = (WeightedSpectrumDataSet*) createBlob("WeightedSpectrumDataSet"); // Create local datablobs spectra = (SpectrumDataSetC32*) createBlob("SpectrumDataSetC32"); stokes = (SpectrumDataSetStokes*) createBlob("SpectrumDataSetStokes"); intStokes = (SpectrumDataSetStokes*) createBlob("SpectrumDataSetStokes"); weightedIntStokes = (WeightedSpectrumDataSet*) createBlob("WeightedSpectrumDataSet"); // Request remote data requestRemoteData("LofarTimeStream1"); }
/* ** External API function used to create a new virtual-table module. */ int sqlite3_create_module_v2( sqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ const sqlite3_module *pModule, /* The definition of the module */ void *pAux, /* Context pointer for xCreate/xConnect */ void (*xDestroy)(void *) /* Module destructor function */ ){ return createModule(db, zName, pModule, pAux, xDestroy); }
// static int TrajectoryAnalysisCommandLineRunner::runAsMain( int argc, char *argv[], ModuleFactoryMethod factory) { auto runnerFactory = [factory] { return createModule(factory()); }; return ICommandLineOptionsModule::runAsMain(argc, argv, NULL, NULL, runnerFactory); }
bool CModuleBuilder::attemptModule() { if( isModuleExist() ) { return true; } if( isAnonymousModule ) { createModule(); return true; } return false; }
/* ** External API function used to create a new virtual-table module. */ int sqlite3_create_module( sqlite3 *db, /* Database in which module is registered */ const char *zName, /* Name assigned to this module */ const sqlite3_module *pModule, /* The definition of the module */ void *pAux /* Context pointer for xCreate/xConnect */ ){ #ifdef SQLITE_ENABLE_API_ARMOR if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT; #endif return createModule(db, zName, pModule, pAux, 0); }
void SWMgr::CreateMods(bool multiMod) { SectionMap::iterator it; ConfigEntMap::iterator start; ConfigEntMap::iterator end; ConfigEntMap::iterator entry; SWModule *newmod; SWBuf driver, misc1; for (it = config->Sections.begin(); it != config->Sections.end(); it++) { ConfigEntMap §ion = (*it).second; newmod = 0; driver = ((entry = section.find("ModDrv")) != section.end()) ? (*entry).second : (SWBuf)""; if (driver.length()) { newmod = createModule((*it).first, driver, section); if (newmod) { // Filters to add for this module and globally announce as an option to the user // e.g. translit, strongs, redletterwords, etc, so users can turn these on and off globally start = (*it).second.lower_bound("GlobalOptionFilter"); end = (*it).second.upper_bound("GlobalOptionFilter"); AddGlobalOptions(newmod, section, start, end); // Only add the option to the module, don't announce it's availability // These are useful for like: filters that parse special entryAttribs in a text // or whatever you might want to happen on entry lookup start = (*it).second.lower_bound("LocalOptionFilter"); end = (*it).second.upper_bound("LocalOptionFilter"); AddLocalOptions(newmod, section, start, end); //STRIP FILTERS // add all basic ones for for the modtype AddStripFilters(newmod, section); // Any special processing for this module when searching: // e.g. for papyri, removed all [](). notation start = (*it).second.lower_bound("LocalStripFilter"); end = (*it).second.upper_bound("LocalStripFilter"); AddStripFilters(newmod, section, start, end); AddRawFilters(newmod, section); AddRenderFilters(newmod, section); AddEncodingFilters(newmod, section); SWModule *oldmod = Modules[newmod->getName()]; if (oldmod) { delete oldmod; } Modules[newmod->getName()] = newmod; } } } }
// static void TrajectoryAnalysisCommandLineRunner::registerModule( CommandLineModuleManager *manager, const char *name, const char *description, ModuleFactoryMethod factory) { auto runnerFactory = [factory] { return createModule(factory()); }; ICommandLineOptionsModule::registerModuleFactory( manager, name, description, runnerFactory); }
BoxedModule* createMainModule(const char* fn) { //static std::unordered_map<AST_Module*, BoxedModule*> made; //assert(made.count(m) == 0); assert(main_module == NULL); std::string s_fn; if (fn != NULL) s_fn = fn; else s_fn = "<stdin>"; std::string name("__main__"); main_module = createModule(&name, &s_fn); return main_module; }
/** * @details * Initialises the pipeline. * * This method is run once on construction of the pipeline. */ void EmbraceBFPipeline::init() { ConfigNode c = config( QString("EmbracePipeline") ); _totalIterations= c.getOption("totalIterations", "value", "10000").toInt(); std::cout << _totalIterations << std::endl; // Create modules // Create modules ppfChanneliser = (PPFChanneliser *) createModule("PPFChanneliser"); embracePowerGenerator = (EmbracePowerGenerator *) createModule("EmbracePowerGenerator"); rfiClipper = (RFI_Clipper *) createModule("RFI_Clipper"); stokesIntegrator = (StokesIntegrator *) createModule("StokesIntegrator"); // Create local datablobs spectra = (SpectrumDataSetC32*) createBlob("SpectrumDataSetC32"); stokes = (SpectrumDataSetStokes*) createBlob("SpectrumDataSetStokes"); intStokes = (SpectrumDataSetStokes*) createBlob("SpectrumDataSetStokes"); weightedIntStokes = (WeightedSpectrumDataSet*) createBlob("WeightedSpectrumDataSet"); // Request remote data requestRemoteData(_streamIdentifier); }
void CModuleBuilder::StartModule( const CToken& startToken ) { if( isModuleExist() ) { fatalError( startToken, ( isAnonymousModule ? "only one anonymous module is allowed in same file" : "alone `start` directive, maybe you lost `end` directive before it" ) ); return; } isAnonymousModule = false; createModule(); module->StartToken = startToken; }
static int __init ModInit(void) { if(createDevice() < 0) { unregister_chrdev_region (my_dev, 1); return -EIO; } if(createModule() < 0) { unregister_chrdev_region (my_dev, 1); return -EIO; } return 0; }
Box* createAndRunModule(BoxedString* name, const std::string& fn) { BoxedModule* module = createModule(name, fn.c_str()); AST_Module* ast = caching_parse_file(fn.c_str(), /* future_flags = */ 0); assert(ast); try { compileAndRunModule(ast, module); } catch (ExcInfo e) { removeModule(name); throw e; } Box* r = getSysModulesDict()->getOrNull(name); if (!r) raiseExcHelper(ImportError, "Loaded module %.200s not found in sys.modules", name->c_str()); return r; }
void setupSys() { sys_modules_dict = new BoxedDict(); gc::registerStaticRootObj(sys_modules_dict); // This is ok to call here because we've already created the sys_modules_dict sys_module = createModule("sys", "__builtin__"); sys_module->giveAttr("modules", sys_modules_dict); BoxedList* sys_path = new BoxedList(); sys_module->giveAttr("path", sys_path); sys_module->giveAttr("argv", new BoxedList()); sys_module->giveAttr("stdout", new BoxedFile(stdout)); sys_module->giveAttr("stdin", new BoxedFile(stdin)); sys_module->giveAttr("stderr", new BoxedFile(stderr)); }
JSValueRef JSCNativeModules::getModule(JSContextRef context, JSStringRef jsName) { std::string moduleName = String::ref(context, jsName).str(); const auto it = m_objects.find(moduleName); if (it != m_objects.end()) { return static_cast<JSObjectRef>(it->second); } auto module = createModule(moduleName, context); if (!module.hasValue()) { return Value::makeUndefined(context); } // Protect since we'll be holding on to this value, even though JS may not module->makeProtected(); auto result = m_objects.emplace(std::move(moduleName), std::move(*module)).first; return static_cast<JSObjectRef>(result->second); }
void setupSys() { sys_modules_dict = new BoxedDict(); gc::registerPermanentRoot(sys_modules_dict); // This is ok to call here because we've already created the sys_modules_dict sys_module = createModule("sys", "__builtin__"); sys_module->giveAttr("modules", sys_modules_dict); BoxedList* sys_path = new BoxedList(); sys_module->giveAttr("path", sys_path); sys_module->giveAttr("argv", new BoxedList()); sys_module->giveAttr("stdout", new BoxedFile(stdout)); sys_module->giveAttr("stdin", new BoxedFile(stdin)); sys_module->giveAttr("stderr", new BoxedFile(stderr)); sys_module->giveAttr("warnoptions", new BoxedList()); sys_module->giveAttr("py3kwarning", False); sys_module->giveAttr("platform", boxStrConstant("unknown")); // seems like a reasonable, if poor, default sys_module->giveAttr("hexversion", boxInt(PY_VERSION_HEX)); sys_module->giveAttr("maxint", boxInt(PYSTON_INT_MAX)); sys_flags_cls = new BoxedClass(type_cls, object_cls, BoxedSysFlags::gcHandler, 0, sizeof(BoxedSysFlags), false); sys_flags_cls->giveAttr("__name__", boxStrConstant("flags")); sys_flags_cls->giveAttr("__new__", new BoxedFunction(boxRTFunction((void*)BoxedSysFlags::__new__, UNKNOWN, 1, 0, true, true))); #define ADD(name) \ sys_flags_cls->giveAttr(STRINGIFY(name), \ new BoxedMemberDescriptor(BoxedMemberDescriptor::OBJECT, offsetof(BoxedSysFlags, name))) ADD(division_warning); ADD(bytes_warning); #undef ADD sys_flags_cls->freeze(); sys_module->giveAttr("flags", new BoxedSysFlags()); }
void Registry::callRegistrar(boost::shared_ptr<ExporterBase> inRegistrar) { if (mRegistrarsCalled.find(inRegistrar) != mRegistrarsCalled.end()) return; std::vector<std::string> deps; inRegistrar->dependencies(deps); for (long k = 0; k < deps.size();k++) { lassert_dump(mExportersByTypeInfo[deps[k]], "no exporter for " << deps[k]); callRegistrar(mExportersByTypeInfo[deps[k]]); } mRegistrarsCalled.insert(inRegistrar); boost::python::scope scope(createModule(inRegistrar->getModuleName())); inRegistrar->exportPythonWrapper(); }
Value JSINativeModules::getModule(Runtime& rt, const PropNameID& name) { if (!m_moduleRegistry) { return nullptr; } std::string moduleName = name.utf8(rt); const auto it = m_objects.find(moduleName); if (it != m_objects.end()) { return Value(rt, it->second); } auto module = createModule(rt, moduleName); if (!module.hasValue()) { // Allow lookup to continue in the objects own properties, which allows for // overrides of NativeModules return nullptr; } auto result = m_objects.emplace(std::move(moduleName), std::move(*module)).first; return Value(rt, result->second); }
JSValueRef JSCNativeModules::getModule(JSContextRef context, JSStringRef jsName) { if (!m_moduleRegistry) { return nullptr; } std::string moduleName = String::ref(context, jsName).str(); const auto it = m_objects.find(moduleName); if (it != m_objects.end()) { return static_cast<JSObjectRef>(it->second); } auto module = createModule(moduleName, context); if (!module.hasValue()) { // Allow lookup to continue in the objects own properties, which allows for overrides of NativeModules return nullptr; } // Protect since we'll be holding on to this value, even though JS may not module->makeProtected(); auto result = m_objects.emplace(std::move(moduleName), std::move(*module)).first; return static_cast<JSObjectRef>(result->second); }
void ModuleList::buildList() { // Load in the xml file, parse it, and build out the controls QDomDocument doc("projects"); QString baseAppPath = ProjectList::getAppPath(); QString projectsPath = baseAppPath + "projects.xml"; QFile file(projectsPath); if(!file.exists()) file.setFileName("projects.xml"); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(mParent, mAppName, "Unable to find projects.xml file.", QMessageBox::Ok, QMessageBox::Ok); return; } if (!doc.setContent(&file)) { file.close(); QMessageBox::critical(mParent, mAppName, "Unable to find projects.xml file.", QMessageBox::Ok, QMessageBox::Ok); return; } file.close(); // Process QDomElement docElem = doc.documentElement(); QDomNode n = docElem.firstChild(); while(!n.isNull()) { QDomElement e = n.toElement(); // try to convert the node to an element. if(!e.isNull() && e.tagName() == "entry") { if(e.hasAttribute("type") && e.attribute("type") == "modules") { QDomNode nModule = e.firstChild(); while(!nModule.isNull()) { QDomElement eModule = nModule.toElement(); if(!eModule.isNull() && eModule.tagName() == "module") { // Work with a module ModuleEntry* module = createModule(eModule); if(module) { if(e.hasAttribute("default")) { module->mDefaultChoice = (e.attribute("default").toInt() == 1); } mModules.push_back(module); } } else if(!eModule.isNull() && eModule.tagName() == "moduleGroup") { // Work with a module group ModuleEntry* moduleGroup = createModuleGroup(eModule); if(moduleGroup) { mModuleGroups.push_back(moduleGroup); } } nModule = nModule.nextSibling(); } } else if(e.hasAttribute("type") && e.attribute("type") == "projectDefines") { QDomNode nPD = e.firstChild(); while(!nPD.isNull()) { QDomElement ePD = nPD.toElement(); if(!ePD.isNull() && ePD.tagName() == "projectDefine") { // Work with a project define ProjectDefineEntry* pd = new ProjectDefineEntry(); pd->mName = ePD.attribute("name"); pd->mDescription = ePD.text(); mProjectDefines.push_back(pd); } nPD = nPD.nextSibling(); } } else if(e.hasAttribute("type") && e.attribute("type") == "moveClasses") { QDomNode nMC = e.firstChild(); while(!nMC.isNull()) { QDomElement eMC = nMC.toElement(); if(!eMC.isNull() && eMC.tagName() == "moveClass") { // Work with a Move class MoveClassEntry* mc = new MoveClassEntry(); mc->mName = eMC.attribute("name"); mc->mDescription = eMC.text(); if(eMC.hasAttribute("default")) { mc->mDefaultChoice = eMC.attribute("default").toInt(); } if(eMC.hasAttribute("donotwrite")) { mc->mDoNotWrite = eMC.attribute("donotwrite").toInt(); } mMoveClasses.push_back(mc); } nMC = nMC.nextSibling(); } } } n = n.nextSibling(); } }
// Find and open a library, and create an instance of a module in that library bool CreateModule(std::string libName, std::string moduleName, boost::shared_ptr<AL::ALBroker> broker, bool verb, bool find) { std::string library; if (find) { // Find the desired library if (verb) std::cout << bold_on << "Finding " << libName << "..." << bold_off << std::endl; library = qi::path::findLib(libName.c_str()); } else { // Use libName as library path library = libName; } // Open the library if(verb) std::cout << bold_on << "Loading " << library << "..." << bold_off << std::endl; void* handle = qi::os::dlopen(library.c_str()); if (!handle) { qiLogWarning(moduleName.c_str()) << "Could not load library:" << qi::os::dlerror() << std::endl; return -1; } // Load the create symbol if(verb) std::cout << bold_on << "Loading _createModule symbol..." << bold_off << std::endl; int(*createModule)(boost::shared_ptr<AL::ALBroker>) = (int(*)(boost::shared_ptr<AL::ALBroker>))(qi::os::dlsym(handle, "_createModule")); if (!createModule) { qiLogWarning(moduleName.c_str()) << "Could not load symbol _createModule: " << qi::os::dlerror() << std::endl; return -1; } // Check if module is already present if(verb) { std::cout << bold_on << "Module " << moduleName << " is "; if (!(broker->isModulePresent(moduleName))) { std::cout << "not "; } std::cout << "present" << bold_off << std::endl; } // Create an instance of the desired module if(verb) std::cout << bold_on << "Creating " << moduleName << " instance..." << bold_off << std::endl; createModule(broker); // Check for module creation if(verb) { std::cout << bold_on << "Module " << moduleName.c_str() << " is "; if (!(broker->isModulePresent(moduleName))) { std::cout << "not "; } std::cout << "present" << bold_off << std::endl; } if (broker->isModulePresent(moduleName)) return true; else return false; }
void setupSys() { sys_modules_dict = new BoxedDict(); constants.push_back(sys_modules_dict); // This is ok to call here because we've already created the sys_modules_dict sys_module = createModule(autoDecref(boxString("sys"))); // sys_module is what holds on to all of the other modules: Py_INCREF(sys_module); late_constants.push_back(sys_module); sys_module->giveAttrBorrowed("modules", sys_modules_dict); BoxedList* sys_path = new BoxedList(); constants.push_back(sys_path); sys_module->giveAttrBorrowed("path", sys_path); sys_module->giveAttr("argv", new BoxedList()); sys_module->giveAttr("exc_info", new BoxedBuiltinFunctionOrMethod(FunctionMetadata::create((void*)sysExcInfo, BOXED_TUPLE, 0), "exc_info", exc_info_doc)); sys_module->giveAttr("exc_clear", new BoxedBuiltinFunctionOrMethod(FunctionMetadata::create((void*)sysExcClear, NONE, 0), "exc_clear", exc_clear_doc)); sys_module->giveAttr( "exit", new BoxedBuiltinFunctionOrMethod(FunctionMetadata::create((void*)sysExit, NONE, 1, false, false), "exit", { None }, NULL, exit_doc)); sys_module->giveAttr("warnoptions", new BoxedList()); sys_module->giveAttrBorrowed("py3kwarning", Py_False); sys_module->giveAttr("byteorder", boxString(isLittleEndian() ? "little" : "big")); sys_module->giveAttr("platform", boxString(Py_GetPlatform())); sys_module->giveAttr("executable", boxString(Py_GetProgramFullPath())); sys_module->giveAttr( "_getframe", new BoxedFunction(FunctionMetadata::create((void*)sysGetFrame, UNKNOWN, 1, false, false), { NULL })); sys_module->giveAttr("_current_frames", new BoxedFunction(FunctionMetadata::create((void*)sysCurrentFrames, UNKNOWN, 0))); sys_module->giveAttr("getdefaultencoding", new BoxedBuiltinFunctionOrMethod( FunctionMetadata::create((void*)sysGetDefaultEncoding, STR, 0), "getdefaultencoding", getdefaultencoding_doc)); sys_module->giveAttr("getfilesystemencoding", new BoxedBuiltinFunctionOrMethod( FunctionMetadata::create((void*)sysGetFilesystemEncoding, STR, 0), "getfilesystemencoding", getfilesystemencoding_doc)); sys_module->giveAttr("getrecursionlimit", new BoxedBuiltinFunctionOrMethod( FunctionMetadata::create((void*)sysGetRecursionLimit, UNKNOWN, 0), "getrecursionlimit", getrecursionlimit_doc)); // As we don't support compile() etc yet force 'dont_write_bytecode' to true. sys_module->giveAttrBorrowed("dont_write_bytecode", Py_True); sys_module->giveAttr("prefix", boxString(Py_GetPrefix())); sys_module->giveAttr("exec_prefix", boxString(Py_GetExecPrefix())); sys_module->giveAttr("copyright", boxString("Copyright 2014-2016 Dropbox.\nAll Rights Reserved.\n\nCopyright (c) 2001-2014 " "Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 " "BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for " "National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) " "1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.")); sys_module->giveAttr("version", boxString(generateVersionString())); sys_module->giveAttr("hexversion", boxInt(PY_VERSION_HEX)); sys_module->giveAttr("subversion", BoxedTuple::create({ autoDecref(boxString("Pyston")), autoDecref(boxString("")), autoDecref(boxString("")) })); sys_module->giveAttr("maxint", boxInt(PYSTON_INT_MAX)); sys_module->giveAttr("maxsize", boxInt(PY_SSIZE_T_MAX)); sys_flags_cls = BoxedClass::create(type_cls, object_cls, 0, 0, sizeof(BoxedSysFlags), false, "flags", false, NULL, NULL, false); sys_flags_cls->giveAttr( "__new__", new BoxedFunction(FunctionMetadata::create((void*)BoxedSysFlags::__new__, UNKNOWN, 1, true, true))); sys_flags_cls->tp_dealloc = (destructor)BoxedSysFlags::dealloc; #define ADD(name) sys_flags_cls->giveAttrMember(STRINGIFY(name), T_OBJECT, offsetof(BoxedSysFlags, name)); ADD(division_warning); ADD(bytes_warning); ADD(no_user_site); ADD(optimize); #undef ADD #define SET_SYS_FROM_STRING(key, value) sys_module->giveAttr((key), (value)) #ifdef Py_USING_UNICODE SET_SYS_FROM_STRING("maxunicode", PyInt_FromLong(PyUnicode_GetMax())); #endif /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */ #ifndef PY_NO_SHORT_FLOAT_REPR SET_SYS_FROM_STRING("float_repr_style", PyString_FromString("short")); #else SET_SYS_FROM_STRING("float_repr_style", PyString_FromString("legacy")); #endif sys_flags_cls->freeze(); auto sys_str = getStaticString("sys"); for (auto& md : sys_methods) { sys_module->giveAttr(md.ml_name, new BoxedCApiFunction(&md, NULL, sys_str)); } sys_module->giveAttrBorrowed("__displayhook__", sys_module->getattr(autoDecref(internStringMortal("displayhook")))); sys_module->giveAttr("flags", new BoxedSysFlags()); }
IModule* ModuleManager::load( const std::string& moduleName ) { SystemState systemState = getSystem()->getState(); if( systemState < SystemState_Initializing ) throw IllegalStateException( "cannot load modules before the system is set up" ); if( systemState > SystemState_Running ) throw IllegalStateException( "cannot load modules while the system is being torn down" ); if( _loaders.empty() ) throw ModuleLoadException( "there are no installed module loaders" ); // check if the module was already loaded IModule* alreadyLoaded = findModule( moduleName ); if( alreadyLoaded ) return alreadyLoaded; /* Load and initialize ModuleParts. Notice that once we initialize a part, it may register a new ModulePartLoader that must also be considered. */ // the IModule is created on demand Module* module = NULL; // for error handling: whether a part was being loaded (true) or initialized (false) bool wasLoading = true; try { size_t numLoaders = _loaders.size(); for( size_t i = 0; i < numLoaders; ++i ) { IModulePartLoader* loader = _loaders[i].get(); if( !loader->canLoadModulePart( moduleName ) ) continue; // load the module part wasLoading = true; RefPtr<IModulePart> part( loader->loadModulePart( moduleName ) ); if( !part.isValid() ) throw ModuleLoadException( "loader returned a null IModulePart" ); if( !module ) module = createModule( moduleName ); module->addPart( part.get() ); // initialize the module part wasLoading = false; part->initialize( module ); // this module part may have added a new IModulePartLoader size_t newNumLoaders = _loaders.size(); assert( newNumLoaders >= numLoaders ); numLoaders = newNumLoaders; } } catch( std::exception& e ) { // any error while loading or initializing a part aborts the whole module if( module ) module->abort(); std::stringstream ss; if( wasLoading ) ss << "error loading module '" << moduleName << "': "; else ss << "exception raised by module '" << moduleName << "' during initialization: "; ss << e.what(); throw ModuleLoadException( ss.str() ); } if( !module ) { CORAL_THROW( ModuleLoadException, "no module loader recognized '" << moduleName << "' as a module (perhaps it was not compiled in " CORAL_BUILD_MODE " mode?)" ); } module->initialize(); syncModuleWithSystemState( module ); return module; }