Esempio n. 1
0
bool Builder::processFile(const String &filename)
{
    // get file extension
    size_t n = filename.rfind(".");
    if (n == std::string::npos)
    {
        THROW_EXCEPT(Exception::ERR_FILE_NOT_FOUND,
                     "Can't determine file extension " + filename,
                     filename, 0);
        return false;
    }

    std::string ext = filename.substr(n + 1, std::string::npos);
    // try to find translator factory
    tTranslatorFactories::iterator it = mTranslatorFactories.find(ext);
    if (it == mTranslatorFactories.end())
    {
        THROW_EXCEPT(Exception::ERR_ITEM_NOT_FOUND,
                     "There are no translators, that support " + ext + " extension",
                     filename, 0);
        return false;
    }

    iTranslator *translator = it->second->createInstance(mContext);
    assert(translator);

    TranslatorParams translateParams;
    translateParams.fileName = filename;
    translateParams.autoFormatInfo = mParams.autoFormatInfo;

    bool result = translator->translate(translateParams);
    delete translator;

    return result;
}
Esempio n. 2
0
CDirect3D9MeshPack::CDirect3D9MeshPack(IDirect3DDevice9Ex* device, const PMeshPack& meshPack)
    : m_meshes(CopyMeshes(meshPack)),
    m_vb(nullptr),
    m_ib(nullptr),
    m_device(device)
{
    assert(m_device);
    assert(meshPack.bits);

    const uint NumVertexBytes = meshPack.firstIndexOffset;
    const uint NumIndexBytes = meshPack.bitsSize - NumVertexBytes;

    HRESULT hr;
    IDirect3DVertexBuffer9* pVb;
    hr = m_device->CreateVertexBuffer(NumVertexBytes, D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT,
        &pVb, NULL);
    if (FAILED(hr))
        THROW_EXCEPT(graphics_device_exception, "Failed to create vertex buffer of size: " + string(DXGetErrorStringA(hr)));
    m_vb = make_directx_unique<IDirect3DVertexBuffer9>(pVb);

    // Copy vertex bits into buffer.
    VOID* bufferPtr;
    hr = m_vb->Lock(0, 0, reinterpret_cast<VOID**>(&bufferPtr), 0);
    if (FAILED(hr))
        THROW_EXCEPT(graphics_device_exception, "Failed to lock vertex buffer: " + string(DXGetErrorStringA(hr)));

    memcpy(bufferPtr, meshPack.bits, NumVertexBytes);
    m_vb->Unlock();

    IDirect3DIndexBuffer9* pIb;
    hr = m_device->CreateIndexBuffer(NumIndexBytes, D3DUSAGE_WRITEONLY, D3DFMT_INDEX32, D3DPOOL_DEFAULT,
        &pIb, NULL);
    if (FAILED(hr))
        THROW_EXCEPT(graphics_device_exception, "Failed to create vertex buffer of size: " + string(DXGetErrorStringA(hr)));
    m_ib = make_directx_unique<IDirect3DIndexBuffer9>(pIb);

    // Copy index bits into buffer.
    hr = m_ib->Lock(0, 0, reinterpret_cast<VOID**>(&bufferPtr), 0);
    if (FAILED(hr))
        THROW_EXCEPT(graphics_device_exception, "Failed to lock index buffer: " + string(DXGetErrorStringA(hr)));

    memcpy(bufferPtr, meshPack.bits + NumVertexBytes, NumIndexBytes);
    m_ib->Unlock();

    // Create vertex declaration.
    m_vdecls.reserve(meshPack.meshesSize);
    for (uint i=0; i<meshPack.meshesSize; ++i) {
        auto vertexDecl = MakeVertexDecl(GetPobStruct(&meshPack, meshes, i));
        IDirect3DVertexDeclaration9* pVdecl;
        hr = m_device->CreateVertexDeclaration(&vertexDecl[0], &pVdecl);
        if (FAILED(hr))
            THROW_EXCEPT(graphics_device_exception, "Failed to create vertex declaration: " + string(DXGetErrorStringA(hr)));
        m_vdecls.emplace_back(shared_ptr<IDirect3DVertexDeclaration9>(pVdecl, directx_deleter<IDirect3DVertexDeclaration9>()));
    }
}
Esempio n. 3
0
I2C::I2C(const std::string &name) : mFilename(name) {
	mLastSlaveAddr = 0x00;

	// Open device
	mFd = open(mFilename.c_str(), O_RDWR);
	if (mFd == -1)
		THROW_EXCEPT(I2CException, "Could not open " + name);

	// Set initial slave to 0; this is defined as a broadcast to all slaves on
	// the line. So mLastSlaveAddr is consistent with internal device driver
	// state.
	if (ioctl(mFd, I2C_SLAVE, mLastSlaveAddr) < 0)
		THROW_EXCEPT(I2CException, "Could not set I2C slave\n");
}
Esempio n. 4
0
size_t I2C::read(uint8_t slaveaddr, void *buffer, size_t length) {
	if (slaveaddr != mLastSlaveAddr) {
		if (ioctl(mFd, I2C_SLAVE, slaveaddr) < 0)
			THROW_EXCEPT(I2CException, "Could not set I2C slave\n");
		else
			mLastSlaveAddr = slaveaddr;
	}

	size_t bytes;
	if ((bytes = ::read(mFd, buffer, length)) == -1)
		THROW_EXCEPT(I2CException, "I2C read operation failed: "
				+ std::string(strerror(errno)));
	return bytes;
}
Esempio n. 5
0
void parseError(const char* errorName, int line)
{
    THROW_EXCEPT(Exception::ERR_PARSE,
                 String(errorName),
                 "",
                 line);
}
Esempio n. 6
0
speed_t RadioLinux::baudToSpeed(int baudrate) {
	switch (baudrate) {
		case 1200:
			return B1200;
		case 1800:
			return B1800;
		case 2400:
			return B2400;
		case 4800:
			return B4800;
		case 9600:
			return B9600;
		case 19200:
			return B19200;
		case 38400:
			return B38400;
		case 57600:
			return B57600;
		case 115200:
			return B115200;
		case 230400:
			return B230400;

		default:
			THROW_EXCEPT(RadioException, "Unsupported baudrate ("
					+ boost::lexical_cast<std::string>(baudrate));
	}
}
Esempio n. 7
0
void SCsTranslator::processSentenceLevel1(pANTLR3_BASE_TREE node)
{
    unsigned int nodesCount = node->getChildCount(node);
    assert(nodesCount == 3);

    pANTLR3_BASE_TREE node_obj = (pANTLR3_BASE_TREE)node->getChild(node, 0);
    pANTLR3_BASE_TREE node_pred = (pANTLR3_BASE_TREE)node->getChild(node, 1);
    pANTLR3_BASE_TREE node_subj = (pANTLR3_BASE_TREE)node->getChild(node, 2);

    pANTLR3_COMMON_TOKEN tok_pred = node_pred->getToken(node_pred);

    if (tok_pred->type != ID_SYSTEM)
    {
        THROW_EXCEPT(Exception::ERR_PARSE,
                     String("Invalid predicate '") + ((const char*) node_pred->getText(node_pred)->chars) + "' in simple sentence",
                     mParams.fileName,
                     tok_pred->getLine(tok_pred));
    }

    sElement *el_obj = parseElementTree(node_obj);
    sElement *el_subj = parseElementTree(node_subj);

    // determine arc type
    sc_type type = sc_type_edge_common;
    String pred = GET_NODE_TEXT(node_pred);
    size_t n = pred.find_first_of("#");
    if (n != pred.npos)
        type = _getArcPreffixType(pred.substr(0, n));

    _addEdge(el_obj, el_subj, type, false, pred);
}
Esempio n. 8
0
void SCsTranslator::processSentenceAssign(pANTLR3_BASE_TREE node)
{
    unsigned int nodesCount = node->getChildCount(node);
    assert(nodesCount == 2);

    pANTLR3_BASE_TREE node_left = (pANTLR3_BASE_TREE)node->getChild(node, 0);
    pANTLR3_BASE_TREE node_right = (pANTLR3_BASE_TREE)node->getChild(node, 1);

    pANTLR3_COMMON_TOKEN tok_left = node_left->getToken(node_left);
    pANTLR3_COMMON_TOKEN tok_right = node_left->getToken(node_right);

    assert(tok_left && tok_right);

    if (tok_left->type != ID_SYSTEM)
    {
        THROW_EXCEPT(Exception::ERR_PARSE,
                     "Unsupported type of tokens at the left side of assignment sentence",
                     mParams.fileName,
                     tok_left->getLine(tok_left));
    }

    if (tok_right->type == ID_SYSTEM)
    {
        mAssignments[GET_NODE_TEXT(node_left)] = GET_NODE_TEXT(node_right);
    }
    else
    {
        String left_idtf = (GET_NODE_TEXT(node_left));
        sElement *el = parseElementTree(node_right, &left_idtf);
    }
}
Esempio n. 9
0
int RadioLinux::readUBE32(uint32_t *i) {
	int bytes;
	uint32_t orig;
	if ((bytes = ::read(mFD, &orig, sizeof(orig))) == -1)
		THROW_EXCEPT(RadioException, "Failed to read from radio");
	BEToHost(i, &orig, sizeof(orig));
	return bytes;
}
Esempio n. 10
0
int RadioLinux::writeUBE32(uint32_t i) {
	int bytes;
	uint32_t swapped;
	hostToBE(&swapped, &i, sizeof(i));
	if ((bytes = ::write(mFD, &swapped, sizeof(swapped))) == -1)
		THROW_EXCEPT(RadioException, "Failed to write to radio");
	return bytes;
}
Esempio n. 11
0
tuple<byte_t*, uint> CDirect3D9DynamicTexture::Lock()
{
    D3DLOCKED_RECT lock;
    HRESULT hr = m_texture->LockRect(0, &lock, NULL, D3DLOCK_DISCARD);
    if (FAILED(hr))
        THROW_EXCEPT(graphics_device_exception, "Failed to lock surface: " + string(DXGetErrorDescriptionA(hr)));
    return make_tuple(static_cast<byte_t*>(lock.pBits), lock.Pitch);
}
Esempio n. 12
0
tuple<byte_t*, uint> CDirect3D9DynamicTexture::Lock(const rect_t& rectangle)
{
    D3DLOCKED_RECT lock;
    const RECT rect = { rectangle.left, rectangle.top, rectangle.right, rectangle.bottom };
    HRESULT hr = m_texture->LockRect(0, &lock, &rect, 0);
    if (FAILED(hr))
        THROW_EXCEPT(graphics_device_exception, "Failed to lock surface: " + string(DXGetErrorDescriptionA(hr)));
    return make_tuple(static_cast<byte_t*>(lock.pBits), lock.Pitch);
}
Esempio n. 13
0
void I2C::write(uint8_t slaveaddr, const void *data, size_t length) {
	if (slaveaddr != mLastSlaveAddr) {
		if (ioctl(mFd, I2C_SLAVE, slaveaddr) < 0)
			THROW_EXCEPT(I2CException, "Could not set I2C slave\n");
		else
			mLastSlaveAddr = slaveaddr;
	}

	int bytes;
	if ((bytes = ::write(mFd, data, length)) < length) {
		int err = errno;
		if (bytes >= 0)
			THROW_EXCEPT(I2CException, "I2C write could not write all bytes");
		else
			THROW_EXCEPT(I2CException, "I2C write operation failed: "
					+ std::string(strerror(err)));
	}
}
Esempio n. 14
0
Motor::Motor(PWM *pwm, int channel, float min_hightime, float max_hightime) {
	mPWM = pwm;
	mChannel = channel;
	mMinHighTime = min_hightime;
	mMaxHighTime = max_hightime;
	mSpeed = -1.0f;

	if (!pwm)
		THROW_EXCEPT(PWMException, "Provided PWM is not valid");

	setSpeed(mSpeed);
}
Esempio n. 15
0
void displayLexerError(pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_UINT8 * tokenNames)
{
    /// modified https://github.com/antlr/antlr3/blob/master/runtime/C/src/antlr3lexer.c

    pANTLR3_LEXER lexer;
    pANTLR3_EXCEPTION ex;
    pANTLR3_STRING ftext;
    lexer = (pANTLR3_LEXER)(recognizer->super);
    ex = lexer->rec->state->exception;

    // See if there is a 'filename' we can use
    String fname = "-unknown source-";
    if (ex->name != NULL)
    {
        ftext = ex->streamName->to8(ex->streamName);
        fname = (const char*)ftext->chars;
    }
    int line = recognizer->state->exception->line;
    StringStream ss ;
    ss << "lexer error " << ex->type << " :\n\t" << (const char*)ex->message << " at offset " << ex->charPositionInLine + 1 << ", ";

    {

        ANTLR3_INT32 width;
        width = ANTLR3_UINT32_CAST(( (pANTLR3_UINT8)(lexer->input->data) + (lexer->input->size(lexer->input) )) - (pANTLR3_UINT8)(ex->index));
        if (width >= 1)
        {
            if	(isprint(ex->c))
                ss << "near '" << ex->c << "' :\n";
            else
            {
                StringStream hs;
                hs << std::hex << std::setfill('0');
                hs << std::setw(2) << ex->c;
                ss << "near char(0x" << hs.str() << ") :\n";
            }
        }
        else
        {
            std::cerr << "(end of input).\n\t This indicates a poorly specified lexer RULE\n\t or unterminated input element such as: \"STRING[\"]\n";
            std::cerr <<  "\t The lexer was matching from line " << (ANTLR3_UINT32)(lexer->rec->state->tokenStartLine) << ", offset "
                      << (ANTLR3_UINT32)(lexer->rec->state->tokenStartCharPositionInLine) << ", which\n\t ";
        }
    }


    THROW_EXCEPT(Exception::ERR_PARSE,
                 ss.str(),
                 fname,
                 line);
}
Esempio n. 16
0
void I2C::sendTransaction() {
	if (mQueue.size() > 0) {
		struct i2c_rdwr_ioctl_data iodata;
		iodata.msgs = &mQueue[0];
		iodata.nmsgs = mQueue.size();

		int iostatus;
		if ((iostatus = ioctl(mFd, I2C_RDWR, &iodata)) < 0)
			THROW_EXCEPT(I2CException, "I2C ioctl() failed: "
					+ std::string(strerror(errno)));

		mQueue.clear();
	}
}
Esempio n. 17
0
bool SCsTranslator::processString(const String &data)
{
    pANTLR3_INPUT_STREAM input;

#if defined( __WIN32__ ) || defined( _WIN32 )
    input = antlr3StringStreamNew((pANTLR3_UINT8)data.c_str(), ANTLR3_ENC_UTF8, (ANTLR3_UINT32)data.length(), (pANTLR3_UINT8)"scs");
#elif defined( __APPLE_CC__)
    input = antlr3StringStreamNew((pANTLR3_UINT8)data.c_str(), ANTLR3_ENC_UTF8, data.length(), (pANTLR3_UINT8)"scs");
#else
    input = antlr3NewAsciiStringCopyStream((pANTLR3_UINT8)data.c_str(), data.length(), (pANTLR3_UINT8)"scs");
#endif

    pscsLexer lex;
    pANTLR3_COMMON_TOKEN_STREAM tokens;
    pscsParser parser;

    lex = scsLexerNew(input);
    tokens = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT,
                                            TOKENSOURCE(lex));
    parser = scsParserNew(tokens);


    scsParser_syntax_return r;
    pANTLR3_BASE_TREE tree;

    try
    {
        r = parser->syntax(parser);
    } catch (const Exception &e)
    {
        THROW_EXCEPT(Exception::ERR_PARSE, e.getDescription(), mParams.fileName, e.getLineNumber());
    }

    tree = r.tree;

    //dumpDot(tree);

    // translate
    buildScText(tree);

    //dumpScs("test.scsd");

    parser->free(parser);
    tokens->free(tokens);
    lex->free(lex);

    input->close(input);

    return true;
}
Esempio n. 18
0
void Controller::init(){
    BB_InstanceContext context;
    initInstanceContext(context);

    _mainInstance = new MainInstance(context);
    try
    {
        _mainInstance->login();
    }
    catch(BB_Exception excp)
    {
        delete _mainInstance;
        _mainInstance = NULL;
        THROW_EXCEPT(excp.GetInfo());
    }
}
Esempio n. 19
0
void Drive::startTimer() {
	if (!mTimerEnabled) {
		mTimerEnabled = true;
		if (pthread_create(&mUpdateThread, NULL, updateThreadEntry, this) != 0) {
			mTimerEnabled = false;
			THROW_EXCEPT(DriveException, "Failed to start update thread");
		}
	}

	/*
	// Establish signal handler
	mTimerAction.sa_sigaction = timerUpdate;
	mTimerAction.sa_flags = SA_SIGINFO;
	sigemptyset(&mTimerAction.sa_mask);

	if (sigaction(SIGALRM, &mTimerAction, NULL) != 0)
		THROW_EXCEPT(DriveException,
				"Could not set signal handler for update routine\n");

	// Create timer that will send signal
	if (mTimerID == 0) {
		mTimerEvent.sigev_notify           = SIGEV_THREAD_ID | SIGEV_SIGNAL;
		mTimerEvent.sigev_signo            = SIGALRM;
		mTimerEvent.sigev_value.sival_ptr  = this;
		mTimerEvent.sigev_notify_thread_id = gettid();

		if (timer_create(CLOCK_REALTIME, &mTimerEvent, &mTimerID) != 0)
			THROW_EXCEPT(DriveException, "Could not create timer");
	}

	// Set timer

	struct itimerspec time;
	time.it_interval.tv_sec  = (mUpdateRate == 1 ? 1 : 0);
	time.it_interval.tv_nsec =
			(mUpdateRate == 1 ? 0 : 1000000000 / mUpdateRate);
	time.it_value.tv_sec  = time.it_interval.tv_sec;
	time.it_value.tv_nsec = time.it_interval.tv_nsec;

	if (timer_settime(mTimerID, 0, &time, NULL) != 0)
		THROW_EXCEPT(DriveException, "Could not start timer");
	*/
}
Esempio n. 20
0
RadioLinux::RadioLinux(const std::string &devfile, int baudrate, Parity p) {
	mBaudRate = baudrate;
	mParity = p;

	mFD = open(devfile.c_str(), O_RDWR | O_ASYNC);
	if (mFD == -1)
		THROW_EXCEPT(RadioException, "Could not open " + devfile);

	struct termios tprops;
	tcgetattr(mFD, &tprops);

	tprops.c_iflag = 0;
	if (mParity != PARITY_NONE)
		tprops.c_iflag |= INPCK;

	tprops.c_oflag = 0;

	tprops.c_cflag = CS8 | CREAD;
	if (mParity != PARITY_NONE) {
		tprops.c_cflag |= PARENB;
		if (mParity == PARITY_ODD)
			tprops.c_cflag |= PARODD;
	}

	tprops.c_lflag = 0;

	// Disable control characaters
	for (int cc = 0; cc < NCCS; ++cc)
		tprops.c_cc[cc] = _POSIX_VDISABLE;

	tprops.c_cc[VMIN]  = 0; // No minimum number of characters for reads
	tprops.c_cc[VTIME] = 0; // No timeout (0 deciseconds)

	speed_t baudspeed = baudToSpeed(mBaudRate);
	cfsetospeed(&tprops, baudspeed);
	cfsetispeed(&tprops, baudspeed);

	tcsetattr(mFD, TCSAFLUSH, &tprops);

	tcflow(mFD, TCOON | TCION);
	tcflush(mFD, TCIOFLUSH);
}
Esempio n. 21
0
CDirect3D9CubeTexture::CDirect3D9CubeTexture(IDirect3DDevice9Ex* device, const PCubeMap& cubeMap)
    : m_device(device)
{
    HRESULT hr;
    D3DFORMAT fmt;

    const int NumFaces = 6;
    const D3DCUBEMAP_FACES faces[NumFaces] = {
        D3DCUBEMAP_FACE_POSITIVE_X,
        D3DCUBEMAP_FACE_NEGATIVE_X,
        D3DCUBEMAP_FACE_POSITIVE_Z,
        D3DCUBEMAP_FACE_NEGATIVE_Z,
        D3DCUBEMAP_FACE_POSITIVE_Y,
        D3DCUBEMAP_FACE_NEGATIVE_Y
    };
    vector<shared_ptr<PTexture>> cubeTexs(NumFaces);
    cubeTexs[0] = GPob->GetTypedPob<PTexture>(cubeMap.positiveX);
    cubeTexs[1] = GPob->GetTypedPob<PTexture>(cubeMap.negativeX);
    cubeTexs[2] = GPob->GetTypedPob<PTexture>(cubeMap.positiveZ);
    cubeTexs[3] = GPob->GetTypedPob<PTexture>(cubeMap.negativeZ);
    cubeTexs[4] = GPob->GetTypedPob<PTexture>(cubeMap.positiveY);
    // Optional bottom face.
    cubeTexs[5] = GPob->GetTypedPob<PTexture>(cubeMap.negativeY);
    if (!cubeTexs[0] || !cubeTexs[1] || !cubeTexs[2] || !cubeTexs[3] || !cubeTexs[4])
        THROW_EXCEPT(graphics_device_exception, "Failed to get cubemap textures");

    // Create the cube texture, using parameters from +X.
    fmt = PixelFormats[static_cast<uint>(cubeTexs[0]->pixelFormat)];
    uint edgeLength = cubeTexs[0]->width;
    IDirect3DCubeTexture9* pCubeMap;
    hr = m_device->CreateCubeTexture(edgeLength, 0, 0, fmt, D3DPOOL_DEFAULT, &pCubeMap, NULL);
    if (FAILED(hr))
        throw graphics_device_exception("Failed to create cube texture: " + string(DXGetErrorStringA(hr)));
    m_cubeMap = make_directx_unique<IDirect3DCubeTexture9>(pCubeMap);

    // Load bits into surface.
    for (int i=0; i < NumFaces; ++i) {
        shared_ptr<PTexture> texture(cubeTexs[i] ? cubeTexs[i] : cubeTexs[0]);
        auto surface = make_directx_unique<IDirect3DSurface9>(LoadTexture(m_device, *texture));
        UpdateCubeMapSurface(faces[i], surface.get());
    }
}
Esempio n. 22
0
int RadioLinux::read(std::string &buffer, size_t numbytes) {
	int bytes, totalbytes = 0, readbytes = 4096;
	char cbuf[4096];
	std::string result;

	if (numbytes > 0)
		readbytes = numbytes;

	while ((bytes = ::read(mFD, cbuf, readbytes)) > 0
			&& (numbytes == 0 || numbytes > 0 && totalbytes < numbytes)) {
		if (bytes == -1)
			THROW_EXCEPT(RadioException, "Failed to read from radio");
		else {
			result.append(cbuf, bytes);
			totalbytes += bytes;
		}
	}

	buffer.assign(result);

	return totalbytes;
}
Esempio n. 23
0
void Drive::loadCalibration(const std::string &filename) {
	std::ifstream file(filename.c_str(), std::ios_base::in);
	if (file.fail())
		THROW_EXCEPT(CalibrationException,
				"Calibration file (" + filename + ") could not be loaded");

	char  key[20];
	float value;
	while (!file.eof()) {
		file.getline(key, 20, '=');

		if (!file.fail()) {
			file >> value;
			file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

			if (strcmp(key, "AccelX") == 0) mAccelOffset.x = value;
			else if (strcmp(key, "AccelY") == 0) mAccelOffset.y = value;
			else if (strcmp(key, "AccelZ") == 0) mAccelOffset.z = value;
			else if (strcmp(key, "GyroX") == 0) mGyroOffset.x = value;
			else if (strcmp(key, "GyroY") == 0) mGyroOffset.y = value;
			else if (strcmp(key, "GyroZ") == 0) mGyroOffset.z = value;
		}
	}
Esempio n. 24
0
bool GwfTranslator::processString(const String &data)
{
    tinyxml2::XMLDocument doc;
    tinyxml2::XMLError error = doc.Parse(data.c_str());

    if (error != tinyxml2::XML_SUCCESS)
    {
        THROW_EXCEPT(Exception::ERR_PARSE,
                     doc.GetErrorStr2(),
                     mParams.fileName,
                     -1);
    }

    tinyxml2::XMLElement *root = doc.FirstChildElement("GWF");
    if (!root)
    {
        THROW_EXCEPT(Exception::ERR_PARSE,
                     "Can't find root element",
                     mParams.fileName,
                     -1);
    }
    root = root->FirstChildElement("staticSector");
    if (!root)
    {
        THROW_EXCEPT(Exception::ERR_PARSE,
                     "Cna't find static sector",
                     mParams.fileName,
                     -1);
    }

    // collect elements
    std::vector<tinyxml2::XMLElement*> nodes;
    std::vector<tinyxml2::XMLElement*> edges;
    std::vector<tinyxml2::XMLElement*> buses;
    std::vector<tinyxml2::XMLElement*> all;

    static std::string s_arc = "arc";
    static std::string s_pair = "pair";
    static std::string s_bus = "bus";

    tinyxml2::XMLElement *el = root->FirstChildElement();
    while (el)
    {
        all.push_back(el);
        if (el->Name() == s_arc || el->Name() == s_pair)
            edges.push_back(el);
        else if (el->Name() == s_bus)
            buses.push_back(el);
        else
            nodes.push_back(el);

        el = el->NextSiblingElement();
    }

    static std::string s_node = "node";
    static std::string s_contour = "contour";

    tStringAddrMap id_map;
    tStringAddrMap::iterator itId;

    // create all nodes
    std::vector<tinyxml2::XMLElement*>::iterator it, itEnd = nodes.end();
    for (it = nodes.begin(); it != itEnd; ++it)
    {
        el = *it;

        String idtf = el->Attribute("idtf");
        String id = el->Attribute("id");
        sc_addr addr;

        itId = id_map.find(id);
        if (itId != id_map.end())
            continue;

        if (idtf.size() > 0)
        {
            if (getScAddr(idtf, addr))
            {
                id_map[id] = addr;
                continue;    // skip elements that already exists
            }
        }

        if (el->Name() == s_contour)
        {
            addr = sc_memory_node_new(sc_type_const | sc_type_node_struct);
            appendScAddr(addr, idtf);
        } else
        {
            tinyxml2::XMLElement *content = el->FirstChildElement("content");
            if (!content)
            {
                THROW_EXCEPT(Exception::ERR_PARSE,
                             "There are no child content for node with id=" + id,
                             mParams.fileName,
                             -1);
            }

            if (content->IntAttribute("type") == 0)
            {
                addr = sc_memory_node_new(convertType(el->Attribute("type")));
                appendScAddr(addr, idtf);
            } else
            {
                // need to create link
                addr = sc_memory_link_new();
                // setup content
                String data = content->GetText();

                if (content->IntAttribute("type") == 4)
                    data = base64_decode(data);

                sc_stream *stream = sc_stream_memory_new(data.c_str(), data.size(), SC_STREAM_READ, SC_FALSE);
                sc_memory_set_link_content(addr, stream);
                sc_stream_free(stream);

                if (mParams.autoFormatInfo)
                {
                    String ext = StringUtil::getFileExtension(content->Attribute("file_name"));
                    if (!ext.empty())
                        generateFormatInfo(addr, ext);
                }
            }
        }

        if (!idtf.empty())
            sc_helper_set_system_identifier(addr, idtf.c_str(), idtf.size());

        id_map[id] = addr;
    }

    // process buses
    itEnd = buses.end();
    for (it = buses.begin(); it != itEnd; ++it)
    {
        el = *it;

        tStringAddrMap::iterator itOwner = id_map.find(el->Attribute("owner"));
        if (itOwner == id_map.end())
            continue;

        id_map[el->Attribute("id")] = itOwner->second;
    }

    // now create edges
    bool created = true;
    while (created)
    {
        created = false;

        itEnd = edges.end();
        for (it = edges.begin(); it != itEnd; ++it)
        {
            el = *it;

            sc_addr addr;
            String id = el->Attribute("id");
            String idtf = el->Attribute("idtf");

            if (id_map.find(id) != id_map.end())
                continue;

            if (getScAddr(idtf, addr))
                continue;

            // get begin and end elements
            tStringAddrMap::iterator itB = id_map.find(el->Attribute("id_b"));
            if (itB == id_map.end())
                continue;

            tStringAddrMap::iterator itE = id_map.find(el->Attribute("id_e"));
            if (itE == id_map.end())
                continue;

            // create arc
            created = true;
            addr = sc_memory_arc_new(convertType(el->Attribute("type")), itB->second, itE->second);
            appendScAddr(addr, idtf);
            id_map[id] = addr;

            if (!idtf.empty())
                sc_helper_set_system_identifier(addr, idtf.c_str(), idtf.size());
        }
    }

    // now append elemnts into contours
    itEnd = all.end();
    for (it = all.begin(); it != itEnd; ++it)
    {
        el = *it;

        tStringAddrMap::iterator itSelf = id_map.find(el->Attribute("id"));
        if (itSelf == id_map.end())
            continue;

        tStringAddrMap::iterator itP = id_map.find(el->Attribute("parent"));
        if (itP == id_map.end())
            continue;

        sc_memory_arc_new(sc_type_arc_pos_const_perm, itP->second, itSelf->second);
    }

    return false;
}
Esempio n. 25
0
int RadioLinux::writeChar(char c) {
	int bytes;
	if ((bytes = ::write(mFD, &c, 1)) == -1)
		THROW_EXCEPT(RadioException, "Failed to write to radio");
	return bytes;
}
Esempio n. 26
0
sElement* SCsTranslator::parseElementTree(pANTLR3_BASE_TREE tree, const String *assignIdtf)
{
    pANTLR3_COMMON_TOKEN tok = tree->getToken(tree);
    assert(tok);

    sElement *res = 0;
    if (tok->type == ID_SYSTEM)
        res = _addNode(GET_NODE_TEXT(tree));

    if (tok->type == SEP_LPAR)
    {
        assert(tree->getChildCount(tree) >= 3);
        pANTLR3_BASE_TREE node_obj = (pANTLR3_BASE_TREE)tree->getChild(tree, 0);
        pANTLR3_BASE_TREE node_pred = (pANTLR3_BASE_TREE)tree->getChild(tree, 1);
        pANTLR3_BASE_TREE node_subj = (pANTLR3_BASE_TREE)tree->getChild(tree, 2);

        String pred = GET_NODE_TEXT(node_pred);
        sElement *src = parseElementTree(node_obj);
        sElement *trg = parseElementTree(node_subj);

        assert(src && trg);

        res = _addEdge(src, trg, _getTypeByConnector(pred), _isConnectorReversed(pred), "");
    }

    if (tok->type == LINK)
    {
        String data = GET_NODE_TEXT(tree);
        CHECK_LINK_DATA(data);
		res = _addLinkFile(assignIdtf ? *assignIdtf : "", data.substr(1, data.size() - 2));
    }

    if (tok->type == CONTENT)
    {
        res = _addNode(assignIdtf ? *assignIdtf : "", sc_type_node_struct);

        String content = GET_NODE_TEXT(tree);
        content = content.substr(1, content.size() - 2);

        if (StringUtil::startsWith(content, "*", false) && StringUtil::endsWith(content, "*", false))
        {
            // parse contour data
            String data = content.substr(1, content.size() - 2);
            bool autoFormatInfo = mParams.autoFormatInfo;
            String fileName = mParams.fileName;

            // check if link to file
            if (StringUtil::startsWith(data, "^\"", false))
            {
                String name;
                bool result = false;
				if (_getAbsFilePath(trimContentData(data), name))
                {
                    fileName = name;
                    std::ifstream ifs(name.c_str());
                    if (ifs.is_open())
                    {
                        data = String((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
                        ifs.close();
                        result = true;
                    } else {
                        THROW_EXCEPT(Exception::ERR_PARSE,
                                     "Can't open file " << name,
                                     mParams.fileName,
                                     tok->getLine(tok));
                    }
                }
            }

            // parse data
            if (!data.empty())
            {
                SCsTranslator translator(mContext);
                translator.mParams.autoFormatInfo = autoFormatInfo;
                translator.mParams.fileName = fileName;
                translator.processString(data);

                // now we need to get all created elements and create arcs to them
                tElementSet::iterator it, itEnd = translator.mElementSet.end();
                for (it = translator.mElementSet.begin(); it != itEnd; ++it)
                {
                    if ((*it)->ignore) continue;

                    sElement *el = new sElement();
                    el->ignore = true;
                    el->addr = (*it)->addr;

                    mElementSet.insert(el);
                    _addEdge(res, el, sc_type_arc_pos_const_perm, false, "");
                }

                // merge identifiers map
                mSysIdtfAddrs.insert(translator.mSysIdtfAddrs.begin(), translator.mSysIdtfAddrs.end());
                mLocalIdtfAddrs.insert(translator.mLocalIdtfAddrs.begin(), translator.mLocalIdtfAddrs.end());
            }


        }
		else
        {
            if (StringUtil::startsWith(content, "^\"", false))
            {
				String data = trimContentData(content);
                CHECK_LINK_DATA(data);
				sBuffer buffer;
								
				if (parseContentBinaryData(data, buffer))
				{
					res = _addLink("", buffer);
				}
				else
				{
					res = _addLinkFile("", data);
				}
            }
            else
            {
                content = StringUtil::replaceAll(content, "\\[", "[");
                content = StringUtil::replaceAll(content, "\\]", "]");
                CHECK_LINK_DATA(content);
                res = _addLinkString("", content);
            }
        }
    }

    if (tok->type == SEP_LTUPLE || tok->type == SEP_LSET)
    {
        res = _addNode("", sc_type_node_tuple);
        processAttrsIdtfList(false, tree, res, "->", tok->type == SEP_LTUPLE);
    }

    // now process internal sentences
    uint32 n = tree->getChildCount(tree);
    for (uint32 i = 0; i < n; ++i)
    {
        pANTLR3_BASE_TREE internal = (pANTLR3_BASE_TREE)tree->getChild(tree, i);
        pANTLR3_COMMON_TOKEN tok = internal->getToken(internal);

        if (tok->type != SEP_LINT) continue;

        // process internal sentences
        uint32 nc = internal->getChildCount(internal);
        for (uint32 j = 0; j < nc; ++j)
        {
            pANTLR3_BASE_TREE node_pred = (pANTLR3_BASE_TREE)internal->getChild(internal, j);
            String connector = GET_NODE_TEXT(node_pred);
            processAttrsIdtfList(false, node_pred, res, connector, false);
        }
    }

    return res;
}
Esempio n. 27
0
sc_addr SCsTranslator::createScAddr(sElement *el)
{
    sc_addr addr;
    SC_ADDR_MAKE_EMPTY(addr);

    if (el->type & sc_type_node)
        addr = sc_memory_node_new(mContext, el->type);
    else if (el->type & sc_type_link)
    {
        addr = sc_memory_link_new(mContext);

        // setup link content
        if (el->link_is_file)
        {
            String file_path;
            if (_getAbsFilePath(el->file_path, file_path))
            {
                sc_stream *stream = sc_stream_file_new(file_path.c_str(), SC_STREAM_FLAG_READ);
                if (stream)
                {
                    sc_memory_set_link_content(mContext, addr, stream);
                    sc_stream_free(stream);
                } else
                {
                    THROW_EXCEPT(Exception::ERR_FILE_NOT_FOUND,
                                 "Can't open file " + el->file_path,
                                 mParams.fileName,
                                 -1);
                }
            } else
            {
                THROW_EXCEPT(Exception::ERR_INVALID_PARAMS,
                             "Unsupported link type  " + el->file_path,
                             mParams.fileName,
                             -1);
            }

        } else
        {           
            sc_stream *stream = sc_stream_memory_new(el->link_data.data.data(), (sc_uint)el->link_data.data.size(), SC_STREAM_FLAG_READ, SC_FALSE);
            sc_memory_set_link_content(mContext, addr, stream);
            sc_stream_free(stream);
        }


        // generate format information
        if (mParams.autoFormatInfo)
        {
            if (el->link_is_file)
            {
				size_t n = el->file_path.find_last_of(".");
                if (n != String::npos)
					generateFormatInfo(addr, el->file_path.substr(n + 1));
            }
        }
    }
    else
    {
        assert(el->arc_src && el->arc_trg);
        if (SC_ADDR_IS_EMPTY(el->arc_src->addr) || SC_ADDR_IS_EMPTY(el->arc_trg->addr))
            return addr;
        addr = sc_memory_arc_new(mContext, el->type, el->arc_src->addr, el->arc_trg->addr);
    }

    el->addr = addr;

    return addr;
}
Esempio n. 28
0
int RadioLinux::readChar(char *c) {
	int bytes;
	if ((bytes = ::read(mFD, c, 1)) == -1)
		THROW_EXCEPT(RadioException, "Failed to read from radio");
	return bytes;
}
Esempio n. 29
0
bool SCsTranslator::buildScText(pANTLR3_BASE_TREE tree)
{
    int nodesCount = tree->getChildCount(tree);
    for (int i = 0; i < nodesCount; ++i)
    {
        pANTLR3_BASE_TREE sentenceNode = (pANTLR3_BASE_TREE)tree->getChild(tree, i);
        eSentenceType sentenceType = determineSentenceType(sentenceNode);
        switch (sentenceType)
        {
        case SentenceLevel1:
            processSentenceLevel1(sentenceNode);
            break;
        case SentenceLevel2_7:
            processSentenceLevel2_7(sentenceNode);
            break;
        case SentenceAssign:
            processSentenceAssign(sentenceNode);
            break;
        case SentenceEOF:
            break;
        default:
            THROW_EXCEPT(Exception::ERR_PARSE,
                        "Unknown sentence type.",
                         mParams.fileName,
                         sentenceNode->getLine(sentenceNode));
            break;
        }
    }

    // now generate sc-text in memory
    tElementSet::iterator it, itEnd = mElementSet.end();
    for (it = mElementSet.begin(); it != itEnd; ++it)
    {
        sElement *el = *it;
        assert(el);

        if (el->type == sc_type_arc_pos_const_perm)
        {
            sc_type type = _getTypeBySetIdtf(el->arc_src->idtf);
            if (type != 0)
            {
                el->ignore = true;
                sc_type newType = el->arc_trg->type | type;
                // TODO check conflicts in sc-type
                if ((type & sc_type_constancy_mask) != 0)
                    newType = (type & sc_type_constancy_mask) | (newType & ~sc_type_constancy_mask);
                el->arc_trg->type = newType;
            }
        }

        // arcs already have types
        if (!(el->type & sc_type_arc_mask))
            determineElementType(el);
    }

    tElementSet arcs;
    for (it = mElementSet.begin(); it != itEnd; ++it)
    {
        sElement *el = *it;
        assert(el);

        // skip processed triples
        if (el->ignore) continue;

        sc_addr addr = resolveScAddr(el);

        if (SC_ADDR_IS_EMPTY(addr))
        {
            assert(el->type & sc_type_arc_mask);
            arcs.insert(el);
        }
    }

    bool created = true;
    while (!arcs.empty() && created)
    {
        created = false;

        tElementSet createdSet;
        itEnd = arcs.end();
        for (it = arcs.begin(); it != itEnd; ++it)
        {
            sElement *arc_el = *it;
            assert(arc_el->type & sc_type_arc_mask);
            sc_addr addr = resolveScAddr(arc_el);

            if (SC_ADDR_IS_EMPTY(addr)) continue;

            createdSet.insert(arc_el);
        }

        created = !createdSet.empty();
        itEnd = createdSet.end();
        for (it = createdSet.begin(); it != itEnd; ++it)
            arcs.erase(*it);
    }

    if (!arcs.empty())
    {
        StringStream ss;
        ss << "Arcs not created: " << arcs.size();
        THROW_EXCEPT(Exception::ERR_INVALID_STATE,
                     ss.str(),
                     mParams.fileName,
                     -1);
    }

    return true;
}
Esempio n. 30
0
void displayRecognitionError (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_UINT8 * tokenNames)
{
    // Adopted code from https://github.com/antlr/antlr3/blob/master/runtime/C/src/antlr3baserecognizer.c
    pANTLR3_EXCEPTION ex;
    pANTLR3_COMMON_TOKEN theToken;
    pANTLR3_BASE_TREE theBaseTree;
    pANTLR3_COMMON_TREE theCommonTree;

    // Retrieve some info for easy reading.
    ex = recognizer->state->exception;
    String fileName;
    // See if there is a 'filename' we can use
    if	(ex->streamName != NULL)
    {
        pANTLR3_STRING ftext;
        ftext = ex->streamName->to8(ex->streamName);
        fileName.assign((const char*)ftext->chars);
    }

    int line = recognizer->state->exception->line;
    StringStream ss;
    ss << (const char*) (recognizer->state->exception->message);

    // How we determine the next piece is dependent on which thing raised the
    // error.
    pANTLR3_STRING ttext;
    switch	(recognizer->type)
    {
    case ANTLR3_TYPE_PARSER:
    {
        // Prepare the knowledge we know we have
        theToken = (pANTLR3_COMMON_TOKEN)(recognizer->state->exception->token);
        ttext = theToken->toString(theToken);
        ss << ", at offset " << recognizer->state->exception->charPositionInLine;
        if (theToken != NULL)
        {
            if (theToken->type == ANTLR3_TOKEN_EOF)
                ss << ", at <EOF>";
            else
                // Guard against null text in a token
                ss << "\n near " << (ttext == NULL ? "<no text for the token>" : (const char*)ttext->chars) << "\n ";
        }
    }
        break;

    case ANTLR3_TYPE_TREE_PARSER:
        theBaseTree = (pANTLR3_BASE_TREE)(recognizer->state->exception->token);
        ttext = theBaseTree->toStringTree(theBaseTree);
        if (theBaseTree != NULL)
        {
            theCommonTree = (pANTLR3_COMMON_TREE) theBaseTree->super;
            if	(theCommonTree != NULL)
            {
                theToken = (pANTLR3_COMMON_TOKEN) theBaseTree->getToken(theBaseTree);
            }
            ss << ", at offset " << theBaseTree->getCharPositionInLine(theBaseTree);
            ss << ", near " << (const char*)ttext->chars;
        }
        break;

    default:
        std::cerr << "Base recognizer function displayRecognitionError called by unknown parser type - provide override for this function\n";
        return;
        break;
    }

    // Although this function should generally be provided by the implementation, this one
    // should be as helpful as possible for grammar developers and serve as an example
    // of what you can do with each exception type. In general, when you make up your
    // 'real' handler, you should debug the routine with all possible errors you expect
    // which will then let you be as specific as possible about all circumstances.
    //
    // Note that in the general case, errors thrown by tree parsers indicate a problem
    // with the output of the parser or with the tree grammar itself. The job of the parser
    // is to produce a perfect (in traversal terms) syntactically correct tree, so errors
    // at that stage should really be semantic errors that your own code determines and handles
    // in whatever way is appropriate.
    switch (ex->type)
    {
    case ANTLR3_UNWANTED_TOKEN_EXCEPTION:
        // Indicates that the recognizer was fed a token which seesm to be
        // spurious input. We can detect this when the token that follows
        // this unwanted token would normally be part of the syntactically
        // correct stream. Then we can see that the token we are looking at
        // is just something that should not be there and throw this exception.
        if	(tokenNames == NULL)
            ss << " : Extraneous input...";
        else
        {
            if	(ex->expecting == ANTLR3_TOKEN_EOF)
                ss << " : Extraneous input - expected <EOF>\n";
            else
                ss << " : Extraneous input - expected " << tokenNames[ex->expecting] << " ...\n";
        }
        break;

    case ANTLR3_MISSING_TOKEN_EXCEPTION:
        // Indicates that the recognizer detected that the token we just
        // hit would be valid syntactically if preceeded by a particular
        // token. Perhaps a missing ';' at line end or a missing ',' in an
        // expression list, and such like.
        if	(tokenNames == NULL)
            ss << " : Missing token (" << ex->expecting << ")...\n";
        else
        {
            if	(ex->expecting == ANTLR3_TOKEN_EOF)
                ss << " : Missing <EOF>\n";
            else
                ss << " : Missing " << tokenNames[ex->expecting] << " \n";
        }
        break;

    case ANTLR3_RECOGNITION_EXCEPTION:
        // Indicates that the recognizer received a token
        // in the input that was not predicted. This is the basic exception type
        // from which all others are derived. So we assume it was a syntax error.
        // You may get this if there are not more tokens and more are needed
        // to complete a parse for instance.
        ss << " : syntax error...\n";
        break;

    case ANTLR3_MISMATCHED_TOKEN_EXCEPTION:
        // We were expecting to see one thing and got another. This is the
        // most common error if we coudl not detect a missing or unwanted token.
        // Here you can spend your efforts to
        // derive more useful error messages based on the expected
        // token set and the last token and so on. The error following
        // bitmaps do a good job of reducing the set that we were looking
        // for down to something small. Knowing what you are parsing may be
        // able to allow you to be even more specific about an error.
        if (tokenNames == NULL)
            ss << " : syntax error...\n";
        else
        {
            if	(ex->expecting == ANTLR3_TOKEN_EOF)
                ss << " : expected <EOF>\n";
            else
                ss << " : expected " << tokenNames[ex->expecting] << " ...\n";
        }
        break;

    case ANTLR3_NO_VIABLE_ALT_EXCEPTION:
        // We could not pick any alt decision from the input given
        // so god knows what happened - however when you examine your grammar,
        // you should. It means that at the point where the current token occurred
        // that the DFA indicates nowhere to go from here.
        ss << " : cannot match to any predicted input...\n";
        break;

    case ANTLR3_MISMATCHED_SET_EXCEPTION:
        {
            ANTLR3_UINT32 count;
            ANTLR3_UINT32 bit;
            ANTLR3_UINT32 size;
            ANTLR3_UINT32 numbits;
            pANTLR3_BITSET errBits;
            // This means we were able to deal with one of a set of
            // possible tokens at this point, but we did not see any
            // member of that set.

            ss << " : unexpected input...\n expected one of : ";
            // What tokens could we have accepted at this point in the
            // parse?
            count = 0;
            errBits = antlr3BitsetLoad	(ex->expectingSet);
            numbits = errBits->numBits	(errBits);
            size = errBits->size	(errBits);

            if (size > 0)
            {
                // However many tokens we could have dealt with here, it is usually
                // not useful to print ALL of the set here. I arbitrarily chose 8
                // here, but you should do whatever makes sense for you of course.
                // No token number 0, so look for bit 1 and on.

                for	(bit = 1; bit < numbits && count < 8 && count < size; bit++)
                {
                    // TODO: This doesn;t look right - should be asking if the bit is set!!
                    if (tokenNames[bit])
                    {
                        ss << (count > 0 ? ", " : "") << tokenNames[bit];
                        count++;
                    }
                }
                ss << "\n";
            }
            else
            {
                std::cerr << "Actually dude, we didn't seem to be expecting anything here, or at least\n";
                std::cerr << "I could not work out what I was expecting, like so many of us these days!\n";
            }
        }
        break;

    case ANTLR3_EARLY_EXIT_EXCEPTION:
        // We entered a loop requiring a number of token sequences
        // but found a token that ended that sequence earlier than
        // we should have done.
        ss << " : missing elements...\n";
        break;

    default:
        // We don't handle any other exceptions here, but you can
        // if you wish. If we get an exception that hits this point
        // then we are just going to report what we know about the
        // token.
        ss << " : syntax not recognized...\n";
        break;
    }

    THROW_EXCEPT(Exception::ERR_PARSE,
                 ss.str(),
                 fileName,
                 line);
}