Example #1
0
//=============================================================================
// METHOD    : SPELLwsFrame::fixState()
//=============================================================================
void SPELLwsFrame::fixState( PyThreadState* newState, bool isHead )
{
	DEBUG("[FRM] Fix state on frame " + PYCREPR(m_frame) + ", head=" + BSTR(isHead));
	// This is required due to how the Python evaluation loop works. The
	// instruction interesting for us is the one after the function call, if
	// the frame is no the head of the tree.
	if (isHead)
	{
		DEBUG("[FRM] Set instruction as head");
		m_lastInstruction--;
	}
	else
	{
		DEBUG("[FRM] Set instruction as intermediate");
		DEBUG("[FRM] Original instruction was " + ISTR(m_lastInstruction));
		DEBUG("[FRM] Last line was " + ISTR(m_lastLine));

		std::string filename = PYSTR(m_frame->f_code->co_filename);
		std::string codename = PYSTR(m_frame->f_code->co_name);
		std::string code_id = filename + "-" + codename;
		int nextLine = SPELLexecutor::instance().getFrame().getModel(code_id).lineAfter(m_lastLine);
		DEBUG("[FRM] Next line is " + ISTR(nextLine));
		int nextInstruction = SPELLexecutor::instance().getFrame().getModel(code_id).offset(nextLine);
		m_lastInstruction = nextInstruction -1; // Will position it in the lastLine but POP_TOP instr.
		DEBUG("[FRM] Set instruction to: " + ISTR(m_lastInstruction));
	}

	DEBUG("[FRM] Applying: INS(" + ISTR(m_lastInstruction) + "), LIN(" + ISTR(m_lastLine) + ") on frame " + PYCREPR(m_frame));

	// Reset the frame values
	m_frame->f_lasti = m_lastInstruction;
	m_frame->f_lineno = m_lastLine;
	m_frame->f_tstate = newState;
	m_frame->f_stacktop = m_frame->f_valuestack;

	// Recover the dynamic data and update the frame
	DEBUG("[FRM] Recovering dynamic data");
	m_dynamic.recover();

	// Connect the head with the thread state (the head is the frame going to
	// be executed after recovery)
	if (isHead)
	{
		newState->frame = m_frame;
	}

	//DumpFrameInfo( m_frame );
	DEBUG("[FRM] State fixed on frame " + PYCREPR(m_frame));
}
Example #2
0
//=============================================================================
// STATIC : SPELLwsWarmStartImpl::shouldFilter()
//=============================================================================
bool SPELLwsWarmStartImpl::shouldFilter( PyObject* key, PyObject* item )
{
	// Do not consider modules
	if (PyModule_Check(item)) return true;
	// Do not consider callables
	if (PyCallable_Check(item)) return true;
	// If there is no filter cannot decide
	if (s_filterKeys == NULL) return false;
	if ( PYSTR(key) == DatabaseConstants::SCDB ) return true;
	if ( PYSTR(key) == DatabaseConstants::GDB ) return true;
	if ( PYSTR(key) == DatabaseConstants::PROC ) return true;
	// If the set contains the key, must filter it
	int contains = PySet_Contains( s_filterKeys, key );
	return contains!=0;
}
Example #3
0
//============================================================================
// FUNCTION        : Step_Call
//============================================================================
static PyObject* Step_Call( PyObject* self, PyObject* args, PyObject* kargs )
{
	std::string stageId = "<\?\?\?>";
	std::string stageTitle = "<\?\?\?>";

	if ((args != NULL)&&(PyTuple_Size(args)==2))
	{
		PyObject* id = PyTuple_GetItem(args,0);
		PyObject* title = PyTuple_GetItem(args,1);
		stageId = PYSTR(id);
		stageTitle = PYSTR(title);
	}
    SPELLexecutor::instance().stageReached(stageId,stageTitle);
    Py_RETURN_NONE;
}
Example #4
0
//============================================================================
// FUNCTION        : Goto_Call
//============================================================================
static PyObject* Goto_Call( PyObject* self, PyObject* args, PyObject* kargs )
{
	PyObject* target = PyTuple_GetItem(args,0);
	std::string label = PYSTR(target);
	SPELLexecutor::instance().goLabel(label,true);
    Py_RETURN_NONE;
}
//=============================================================================
// METHOD    : SPELLwsClassDataHandler::read()
//=============================================================================
void SPELLwsClassDataHandler::read()
{
	// Store the class name
	SPELLwsObjectDataHandler nameHandler( NULL );
	nameHandler.setStorage(getStorage());
	SPELLwsDictDataHandler dictHandler( NULL );
	dictHandler.setStorage(getStorage());

	// Read the data
	DEBUG("[CDH] Reading name");
	nameHandler.read();
	DEBUG("[CDH] Name read: " + PYREPR(nameHandler.getObject()));

	PyObject* classObject = NULL;
	if ( PYSTR(nameHandler.getObject()) == "__FAILED_WS_CLASS__" )
	{
		classObject = PyClass_New( NULL, PyDict_New(), nameHandler.getObject() );
		std::string msg = "Detected failed WS class, assuming error during marshal process";
		LOG_ERROR(msg);
		std::cerr << msg << std::endl;
	}
	else
	{
		DEBUG("[CDH] Reading dictionary");
		dictHandler.read();
		DEBUG("[CDH] Dictionary read: " + PYREPR(dictHandler.getObject()));
		// Create the class object
		classObject = PyClass_New( NULL, dictHandler.getObject(), nameHandler.getObject() );
	}
	// Set it as associated object
	setObject( classObject );
}
//=============================================================================
// CONSTRUCTOR : SPELLvariableMonitor::SPELLvariableMonitor
//=============================================================================
SPELLvariableMonitor::SPELLvariableMonitor( SPELLvariableChangeListener* listener,
		                                    PyFrameObject* frame,
		                                    std::set<std::string>& initialVariables)
: m_frame(frame),
  m_listener(listener),
  m_initialVariables(initialVariables)
{
	DEBUG("[VM] Created frame for code " + PYSTR(m_frame->f_code->co_name));
}
Example #7
0
void get_arg::get_arg_base::finished() {
    // are there more keywords than we used?
    if(UNLIKELY(kwds && kcount < PyDict_Size(kwds))) {
        PyObject *key;
        Py_ssize_t pos = 0;
        while(PyDict_Next(kwds,&pos,&key,NULL)){
            if(!PYSTR(Check)(key)) {
                PyErr_SetString(PyExc_TypeError,"keywords must be strings");
                throw py_error_set();
            }
#if PY_MAJOR_VERSION >= 3
  #if PY_MINOR_VERSION >= 3
            const char *kstr = PyUnicode_AsUTF8(key);
            if(!kstr) throw py_error_set();
  #else
            PyObject *kstr_obj = PyUnicode_AsUTF8String(key);
            if(!kstr_obj) throw py_error_set();
            
            struct deleter {
                PyObject *ptr;
                deleter(PyObject *ptr) : ptr(ptr) {}
                ~deleter() { Py_DECREF(ptr); }
            } _(kstr_obj);
            
            const char *kstr = PyBytes_AS_STRING(kstr_obj);
  #endif
#else
            const char *kstr = PyBytes_AS_STRING(key);
#endif
            if(names) {
                for(const char **name = names; *name; ++name) {
                    if(strcmp(kstr,*name) == 0) goto match;
                }
            }
                
            PyErr_Format(PyExc_TypeError,"'%s' is an invalid keyword argument for %s%s",
                kstr,
                fname ? fname : "this function",
                fname ? "()" : "");
            throw py_error_set();
            
        match:
            ;
        }
        
        // should never reach here
        assert(false);
    }
}
Example #8
0
//=============================================================================
// METHOD    : SPELLcifHelper::generatePromptOptions()
//=============================================================================
void SPELLcifHelper::generatePromptOptions( PyObject* args, SPELLpromptDefinition& def )
{
    SPELLpyArgs argumentsA(args);

    PyObject* optionsObj = argumentsA[1];
    PyObject* configObj = argumentsA[2];

	def.defaultAnswer = "";

    SPELLpyArgs argumentsC(args,configObj);

    std::string deflt = "";
	if (argumentsC.hasModifier(LanguageModifiers::Default))
	{
		deflt = argumentsC.getModifier_Default();
	}

    if ((optionsObj != NULL)&&(PyList_Size(optionsObj)>0))
    {
        LOG_INFO("Using options object");

    	int listSize = PyList_Size(optionsObj);
    	DEBUG("[CIF PY] Number of prompt options: " + ISTR(listSize))
    	for(int keyIndex=0; keyIndex<listSize; keyIndex++)
    	{
    		PyObject* item = PyList_GetItem(optionsObj, keyIndex);
    		std::string optionString = PYSTR(item);

    		std::string key = "";

    		// ALPHA option
    		bool alpha = false;
    		if (argumentsC.hasModifier(LanguageModifiers::Type))
    		{
    			int type = PyLong_AsLong(argumentsC[LanguageModifiers::Type]);
    			alpha = (( type & LanguageConstants::PROMPT_ALPHA ) > 0 && (type & LanguageConstants::PROMPT_LIST) > 0);
    		}

    		if (alpha)
    		{
				if ( optionString.find(":") == std::string::npos )
				{
					key = optionString;
				}
				else
				{
					// If in alhpa and either way a colon is provided, remove it
					int idx = optionString.find(":");
					optionString = optionString.substr(idx+1, optionString.size()-idx);
					SPELLutils::trim(optionString);
					key = optionString;
				}
    		}
    		else
    		{
				if ( optionString.find(":") == std::string::npos )
				{
					// Put an internal key in this case
					key = ISTR(keyIndex+1);
				}
				else
				{
					int idx = optionString.find(":");
					key = optionString.substr(0, idx);
					// Trim the key
					SPELLutils::trim(key);
				}
    		}
    		def.options.push_back( optionString );
            def.expected.push_back(key);
    	}

    	if (deflt != "")
    	{
    		std::vector<std::string>::iterator it = std::find(def.expected.begin(),def.expected.end(),deflt);
    		if (it != def.expected.end())
    		{
    			def.defaultAnswer = deflt;
    		}
    	}
    }
Example #9
0
//============================================================================
// METHOD: SPELLpyValue::set
//============================================================================
void SPELLpyValue::set( PyObject* pyValue )
{
	m_type = NONE;
	m_intValue = 0;
	m_boolValue = false;
	m_floatValue = 0.0;
	m_timeValue.set(0,0);
	m_stringValue = "";

	if (pyValue == NULL) return;

	DEBUG("[PYVAL] Set value from " + PYREPR(pyValue));
	if (pyValue != Py_None)
	{
		if (PyBool_Check(pyValue))
		{
			m_type = BOOLEAN;
			m_boolValue = pyValue == Py_True;
		}
		else if (PyLong_Check(pyValue))
		{
			DEBUG("[PYVAL] Long check");
			m_type = LONG;
			m_intValue = PyLong_AsLongLong(pyValue);
		}
		else if (PyInt_Check(pyValue))
		{
			DEBUG("[PYVAL] Int check");
			m_type = LONG;
			m_intValue = PyInt_AsLong(pyValue);
		}
		else if (PyFloat_Check(pyValue))
		{
			m_type = DOUBLE;
			m_floatValue = PyFloat_AsDouble(pyValue);
		}
		else if (SPELLpythonHelper::instance().isTime(pyValue))
		{
			m_timeValue = SPELLpythonHelper::instance().evalTime(PYSSTR(pyValue));
			if (m_timeValue.isDelta())
			{
				m_type = RELTIME;
			}
			else
			{
				m_type = ABSTIME;
			}
		}
		else if (PyString_Check(pyValue))
		{
			m_type = STRING;
			m_stringValue = PYSTR(pyValue);
		}
		else if (PyList_Check(pyValue))
		{
			m_type = LIST;
			m_listValue.clear();
			unsigned int numItems = PyList_Size(pyValue);
			for(unsigned int idx = 0; idx < numItems; idx++)
			{
				m_listValue.push_back( SPELLpyValue( PyList_GetItem( pyValue, idx) ));
			}
		}
		else if (PyDict_Check(pyValue))
		{
			m_type = DICT;
			m_dictValue.clear();
			PyObject* keys = PyDict_Keys(pyValue);
			unsigned int numItems = PyList_Size(keys);
			for(unsigned int idx = 0; idx < numItems; idx++)
			{
				PyObject* key = PyList_GetItem(keys,idx);
				PyObject* value = PyDict_GetItem( pyValue, key );
				m_dictValue.insert( std::make_pair( PYSSTR(key), SPELLpyValue(value) ) );
			}
		}
		else
		{
			THROW_EXCEPTION("Cannot create variable value",
					        "Cannot infer type from value (" + PYREPR(pyValue) + ")",
					        SPELL_ERROR_LANGUAGE);
		}
		SPELLpythonHelper::instance().checkError();
	}
}
Example #10
0
//============================================================================
// FUNCTION        : Log_Call
//============================================================================
static PyObject* Log_Call( PyObject* self, PyObject* args, PyObject* kargs )
{
    char* message     = (char*)"";
    LogSeverity sev   = LOG_INFO;
    LogLevel    level = LOG_PROC;

    int size = PyTuple_Size(args);
    if (size==1)
    {
        if (!PyArg_ParseTuple(args,"s", &message))
        {
            THROW_SYNTAX_EXCEPTION("Cannot log message", "Wrong arguments");
        }
        if (kargs != NULL)
        {
            if (PyDict_Contains( kargs, KEY_SEVERITY ))
            {
                std::string value = PYSTR(PyDict_GetItemString( kargs, "severity" ));
                sev = str_to_sev.find(value)->second;

            }
            if (PyDict_Contains( kargs, KEY_LEVEL ))
            {
                std::string value = PYSTR(PyDict_GetItemString( kargs, "level" ));
                level = str_to_lev.find(value)->second;
            }
        }
    }
    else if (size == 2)
    {
        char* psev = (char*) "";
        if (!PyArg_ParseTuple(args,"ss", &message, &psev))
        {
            THROW_SYNTAX_EXCEPTION("Cannot log message", "Wrong arguments");
        }
        if (kargs != NULL)
        {
            if (PyDict_Contains( kargs, KEY_LEVEL ))
            {
                std::string value = PYSTR(PyDict_GetItemString( kargs, "level" ));
                level = str_to_lev.find(value)->second;
            }
        }
        sev = str_to_sev.find(STR(psev))->second;
    }
    else if (size == 3)
    {
        char* psev = (char*) "";
        char* plev = (char*) "";
        if (!PyArg_ParseTuple(args,"sss", &message, &psev, &plev))
        {
            THROW_SYNTAX_EXCEPTION("Cannot log message", "Wrong arguments");
        }
        sev = str_to_sev.find(STR(psev))->second;
        level = str_to_lev.find(STR(plev))->second;
    }
    else
    {
        THROW_SYNTAX_EXCEPTION("Cannot log message", "Wrong arguments");
    }
    SPELLlog::instance().log(message, sev, level);
    Py_RETURN_NONE;
}