Example #1
0
PgmSP parse(void)
{
	token = getToken();
	--runlevel;
	return PgmB();
}
Example #2
0
/*
** Run the parser on the given SQL string.  The parser structure is
** passed in.  An SQLITE_ status code is returned.  If an error occurs
** and pzErrMsg!=NULL then an error message might be written into 
** memory obtained from malloc() and *pzErrMsg made to point to that
** error message.  Or maybe not.
*/
int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  int nErr = 0;
  int i;
  void *pEngine;
  int tokenType;
  int lastTokenParsed = -1;
  sqlite3 *db = pParse->db;
  extern void *sqlite3ParserAlloc(void*(*)(int));
  extern void sqlite3ParserFree(void*, void(*)(void*));
  extern int sqlite3Parser(void*, int, Token, Parse*);

  db->flags &= ~SQLITE_Interrupt;
  pParse->rc = SQLITE_OK;
  i = 0;
  pEngine = sqlite3ParserAlloc((void*(*)(int))malloc);
  if( pEngine==0 ){
    sqlite3SetString(pzErrMsg, "out of memory", (char*)0);
    return 1;
  }
  assert( pParse->sLastToken.dyn==0 );
  assert( pParse->pNewTable==0 );
  assert( pParse->pNewTrigger==0 );
  assert( pParse->nVar==0 );
  assert( pParse->nVarExpr==0 );
  assert( pParse->nVarExprAlloc==0 );
  assert( pParse->apVarExpr==0 );
  pParse->zTail = pParse->zSql = zSql;
  while( sqlite3_malloc_failed==0 && zSql[i]!=0 ){
    assert( i>=0 );
    pParse->sLastToken.z = &zSql[i];
    assert( pParse->sLastToken.dyn==0 );
    pParse->sLastToken.n = getToken((unsigned char*)&zSql[i],&tokenType);
    i += pParse->sLastToken.n;
    switch( tokenType ){
      case TK_SPACE:
      case TK_COMMENT: {
        if( (db->flags & SQLITE_Interrupt)!=0 ){
          pParse->rc = SQLITE_INTERRUPT;
          sqlite3SetString(pzErrMsg, "interrupt", (char*)0);
          goto abort_parse;
        }
        break;
      }
      case TK_ILLEGAL: {
        if( pzErrMsg ){
          sqliteFree(*pzErrMsg);
          *pzErrMsg = sqlite3MPrintf("unrecognized token: \"%T\"",
                          &pParse->sLastToken);
        }
        nErr++;
        goto abort_parse;
      }
      case TK_SEMI: {
        pParse->zTail = &zSql[i];
        /* Fall thru into the default case */
      }
      default: {
        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
        lastTokenParsed = tokenType;
        if( pParse->rc!=SQLITE_OK ){
          goto abort_parse;
        }
        break;
      }
    }
  }
abort_parse:
  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
    if( lastTokenParsed!=TK_SEMI ){
      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
      pParse->zTail = &zSql[i];
    }
    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  }
  sqlite3ParserFree(pEngine, free);
  if( sqlite3_malloc_failed ){
    pParse->rc = SQLITE_NOMEM;
  }
  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
    sqlite3SetString(&pParse->zErrMsg, sqlite3ErrStr(pParse->rc),
                    (char*)0);
  }
  if( pParse->zErrMsg ){
    if( pzErrMsg && *pzErrMsg==0 ){
      *pzErrMsg = pParse->zErrMsg;
    }else{
      sqliteFree(pParse->zErrMsg);
    }
    pParse->zErrMsg = 0;
    if( !nErr ) nErr++;
  }
  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
    sqlite3VdbeDelete(pParse->pVdbe);
    pParse->pVdbe = 0;
  }
  sqlite3DeleteTable(pParse->db, pParse->pNewTable);
  sqlite3DeleteTrigger(pParse->pNewTrigger);
  sqliteFree(pParse->apVarExpr);
  if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
    pParse->rc = SQLITE_ERROR;
  }
  return nErr;
}
Example #3
0
struct assignNode* expr(struct assignNode* assign)
{
	struct varNode* oper1;
	struct varNode* oper2;
	int oper;

	ttype = getToken();
	if (ttype == NUM)
	{	
		printf("NUM: %d\n",ttype);
		assign->op1 = primary();

		ttype = getToken();
		if ((ttype == PLUS) | (ttype == MINUS) | (ttype == MULT) | (ttype == DIV))
		{	
			assign->oper = ttype; //op is set + - * /
			assign->op2 = primary();
		}
		
		ungetToken();
		return assign;
	} 
	else if (ttype == ID)
	{
		printf("ID: %d\n",ttype);
		//oper1 = symSearch(token);

		/*if(oper1 != NULL)
		//{
			//assign->op1->id = oper1->vID;*/
			assign->op1 = primary();
			printf("ASSIGN ID %s\n", assign->op1->id);
			
			ttype = getToken();
			printf("PLUS: %d\n",ttype);
			if ((ttype == PLUS) | (ttype == MINUS) | (ttype == MULT) | (ttype == DIV))
			{
				assign->oper = ttype;
				
				ttype = getToken();
				if(ttype == ID) 
				
				{
	printf("ID: %d\n",ttype);				
					/*oper2 = symSearch(token);
					
					
					//printf("oper2: %s\n",oper2->vID);
					//if(oper2 != NULL) 
					
					//{
						
						//assign->op2 = oper2;
						//assign->op2->id = oper1->vID;
*/							
						
						/*ttype = getToken();
						
						printf("SEMICOLON: %d\n",ttype);
						if(ttype == SEMICOLON)
						
						{
		
							//ungetToken();
*/
							assign->op2 = primary();
							return assign;						
						/*}
						
						else
						
						{
							
							return NULL;
						
						}
	*/				
					/*} 
					
					//else 
					
					//{
						
					//	return NULL;
					
					//}
*/				
				} 
				
				else
				
				{
					
					ungetToken();
				
				}
		
			} 
			
			else 
			
			{
				
				return NULL;
			
			}
		
		//}
	
	 }
}
Example #4
0
Group* SceneParser::parseTriangleMesh() {
  char token[MAX_PARSER_TOKEN_LENGTH];
  char filename[MAX_PARSER_TOKEN_LENGTH];
  // get the filename
  getToken(token); assert (!strcmp(token, "{"));
  getToken(token); assert (!strcmp(token, "obj_file"));
  getToken(filename); 
  getToken(token); assert (!strcmp(token, "}"));
  const char *ext = &filename[strlen(filename)-4];
  assert(!strcmp(ext,".obj"));
  // read it once, get counts
  FILE *file = fopen(filename,"r");
  assert (file != NULL);
  int vcount = 0; int fcount = 0;
  while (1) {
    int c = fgetc(file);
    if (c == EOF) { break;
    } else if (c == 'v') { 
      assert(fcount == 0); float v0,v1,v2;
      fscanf (file,"%f %f %f",&v0,&v1,&v2);
      vcount++; 
    } else if (c == 'f') {
      int f0,f1,f2;
      fscanf (file,"%d %d %d",&f0,&f1,&f2);
      fcount++; 
    } // otherwise, must be whitespace
  }
  fclose(file);
  // make arrays
  Vec3f *verts = new Vec3f[vcount];
  Group *answer = new Group(fcount);
  // read it again, save it
  file = fopen(filename,"r");
  assert (file != NULL);
  int new_vcount = 0; int new_fcount = 0;
  while (1) {
    int c = fgetc(file);
    if (c == EOF) { break;
    } else if (c == 'v') { 
      assert(new_fcount == 0); float v0,v1,v2;
      fscanf (file,"%f %f %f",&v0,&v1,&v2);
      verts[new_vcount] = Vec3f(v0,v1,v2);
      new_vcount++; 
    } else if (c == 'f') {
      assert (vcount == new_vcount);
      int f0,f1,f2;
      fscanf (file,"%d %d %d",&f0,&f1,&f2);
      // indexed starting at 1...
      assert (f0 > 0 && f0 <= vcount);
      assert (f1 > 0 && f1 <= vcount);
      assert (f2 > 0 && f2 <= vcount);
      assert (current_material != NULL);
      Triangle *t = new Triangle(verts[f0-1],verts[f1-1],verts[f2-1],current_material);
      answer->addObject(new_fcount,t);
      new_fcount++; 
    } // otherwise, must be whitespace
  }
  delete [] verts;
  assert (fcount == new_fcount);
  assert (vcount == new_vcount);
  fclose(file);
  return answer;
}
Example #5
0
void *MsgViewBase::processEvent(Event *e)
{
    if (e->type() == EventMessageDeleted){
        Message *msg = (Message*)(e->param());
        if (msg->contact() != m_id)
            return NULL;
        for (unsigned i = 0; i < (unsigned)paragraphs(); i++){
            QString s = text(i);
            int n = s.find(MSG_HREF);
            if (n < 0)
                continue;
            s = s.mid(n + strlen(MSG_HREF));
            n = s.find("\"");
            if (n < 0)
                continue;
            s = s.left(n);
            unsigned id = atol(getToken(s, ',').latin1());
            if (id != msg->id())
                continue;
            getToken(s, ',');
            if (s != msg->client())
                continue;
            unsigned j;
            for (j = i + 1; j < (unsigned)paragraphs(); j++){
                QString s = text(j);
                if (s.find(MSG_HREF) >= 0)
                    break;
            }
            int paraFrom, indexFrom;
            int paraTo, indexTo;
            getSelection(&paraFrom, &indexFrom, &paraTo, &indexTo);
            setSelection(i, 0, j - 1, 0xFFFF);
            setReadOnly(false);
            removeSelectedText();
            setReadOnly(true);
            if ((paraFrom == -1) && (paraTo == -1)){
                scrollToBottom();
            }else{
                setSelection(paraFrom, indexFrom, paraTo, indexTo);
            }
            break;
        }
        return NULL;
    }
    if (e->type() == EventMessageRead){
        Message *msg = (Message*)(e->param());
        if (msg->contact() != m_id)
            return NULL;
        for (unsigned i = 0; i < (unsigned)paragraphs(); i++){
            QString s = text(i);
            int n = s.find(MSG_HREF);
            if (n < 0)
                continue;
            s = s.mid(n + strlen(MSG_HREF));
            n = s.find("\"");
            if (n < 0)
                continue;
            s = s.left(n);
            unsigned id = atol(getToken(s, ',').latin1());
            if (id != msg->id())
                continue;
            getToken(s, ',');
            if (s != msg->client())
                continue;
            int paraFrom, indexFrom;
            int paraTo, indexTo;
            getSelection(&paraFrom, &indexFrom, &paraTo, &indexTo);
            setSelection(i, 0, i, 0xFFFF);
            setBold(false);
            if ((paraFrom == -1) && (paraTo == -1)){
                removeSelection();
                scrollToBottom();
            }else{
                setSelection(paraFrom, indexFrom, paraTo, indexTo);
            }
            break;
        }
        return NULL;
    }
    if (e->type() == EventHistoryConfig){
        unsigned id = (unsigned)(e->param());
        if (id && (id != m_id))
            return NULL;
        QString t;
        for (unsigned i = 0; i < (unsigned)paragraphs(); i++){
            QString s = text(i);
            int n = s.find(MSG_HREF);
            if (n < 0)
                continue;
            s = s.mid(n + strlen(MSG_HREF));
            n = s.find("\"");
            if (n < 0)
                continue;
            s = s.left(n);
            unsigned id = atol(getToken(s, ',').latin1());
            getToken(s, ',');
            Message *msg = History::load(id, s.utf8(), m_id);
            if (msg == NULL)
                continue;
            t += messageText(msg);
            delete msg;
        }
        QPoint p = QPoint(0, height());
        p = mapToGlobal(p);
        p = viewport()->mapFromGlobal(p);
        int x, y;
        viewportToContents(p.x(), p.y(), x, y);
        int para;
        int pos = charAt(QPoint(x, y), &para);
        setText(t);
        if (!CorePlugin::m_plugin->getOwnColors())
            setBackground(0);
        if (pos == -1){
            scrollToBottom();
        }else{
            setCursorPosition(para, pos);
            ensureCursorVisible();
        }
    }
    if (e->type() == EventHistoryColors){
        setColors();
    }
    if (e->type() == EventCheckState){
        CommandDef *cmd = (CommandDef*)(e->param());
        if ((cmd->param != this) || (cmd->menu_id != MenuMsgView))
            return NULL;
        Message *msg;
        switch (cmd->id){
        case CmdCopy:
            cmd->flags &= ~(COMMAND_DISABLED | COMMAND_CHECKED);
            if (!hasSelectedText())
                cmd->flags |= COMMAND_DISABLED;
            return e->param();
        case CmdMsgOpen:
            msg = currentMessage();
            if (msg){
                unsigned type = msg->type();
                delete msg;
                for (;;){
                    CommandDef *def = CorePlugin::m_plugin->messageTypes.find(type);
                    if (def == NULL){
                        return NULL;
                    }
                    MessageDef *mdef = (MessageDef*)(def->param);
                    if (mdef->base_type){
                        type = mdef->base_type;
                        continue;
                    }
                    cmd->icon = def->icon;
                    cmd->flags &= ~COMMAND_CHECKED;
                    return e->param();
                }
            }
            return NULL;
        case CmdMsgSpecial:
            msg = currentMessage();
            if (msg){
                Event eMenu(EventGetMenuDef, (void*)MenuMsgCommand);
                CommandsDef *cmdsMsg = (CommandsDef*)(eMenu.process());

                unsigned n = 0;
                MessageDef *mdef = NULL;
                if (msg->getFlags() & MESSAGE_RECEIVED){
                    unsigned type = msg->type();
                    for (;;){
                        CommandDef *msgCmd = CorePlugin::m_plugin->messageTypes.find(type);
                        if (msgCmd == NULL)
                            break;
                        mdef = (MessageDef*)(msgCmd->param);
                        if (mdef->base_type == 0)
                            break;
                        type = mdef->base_type;
                    }
                }
                if (mdef && mdef->cmd){
                    for (const CommandDef *d = mdef->cmd; d->text; d++)
                        n++;
                }

                {
                    CommandsList it(*cmdsMsg, true);
                    while (++it)
                        n++;
                }
                if (n == 0)
                    return NULL;

                n++;
                CommandDef *cmds = new CommandDef[n];
                memset(cmds, 0, sizeof(CommandDef) * n);
                n = 0;
                if (mdef && mdef->cmd){
                    for (const CommandDef *d = mdef->cmd; d->text; d++){
                        cmds[n] = *d;
                        cmds[n].id = CmdMsgSpecial + n;
                        n++;
                    }
                }
                CommandDef *c;
                CommandsList it(*cmdsMsg, true);
                while ((c = ++it) != NULL){
                    CommandDef cmd = *c;
                    cmd.menu_id = MenuMsgCommand;
                    cmd.param   = msg;
                    Event e(EventCheckState, &cmd);
                    if (!e.process())
                        continue;
                    cmd.flags &= ~COMMAND_CHECK_STATE;
                    cmds[n++] = cmd;
                }
                cmd->param = cmds;
                cmd->flags |= COMMAND_RECURSIVE;
                delete msg;
                return e->param();
            }
            return NULL;
        }
    }
    if (e->type() == EventCommandExec){
        CommandDef *cmd = (CommandDef*)(e->param());
        if ((cmd->param != this) || (cmd->menu_id != MenuMsgView))
            return NULL;
        Message *msg;
        switch (cmd->id){
        case CmdCopy:
            copy();
            return e->param();
        case CmdMsgOpen:
            msg = currentMessage();
            if (msg){
                msg->setFlags(msg->getFlags() | MESSAGE_OPEN);
                Event eOpen(EventOpenMessage, msg);
                eOpen.process();
                delete msg;
                return e->param();
            }
            return NULL;
        default:
            msg = currentMessage();
            if (msg){
                if (cmd->id >= CmdMsgSpecial){
                    MessageDef *mdef = NULL;
                    unsigned type = msg->type();
                    for (;;){
                        CommandDef *msgCmd = CorePlugin::m_plugin->messageTypes.find(type);
                        if (msgCmd == NULL)
                            break;
                        mdef = (MessageDef*)(msgCmd->param);
                        if (mdef->base_type == 0)
                            break;
                        type = mdef->base_type;
                    }
                    if (mdef && mdef->cmd){
                        unsigned n = cmd->id - CmdMsgSpecial;
                        for (const CommandDef *d = mdef->cmd; d->text; d++){
                            if (n-- == 0){
                                CommandDef cmd = *d;
                                cmd.param = msg;
                                Event eCmd(EventCommandExec, &cmd);
                                eCmd.process();
                                return e->param();
                            }
                        }
                    }
                }
                Command c;
                c->id = cmd->id;
                c->menu_id = MenuMsgCommand;
                c->param = msg;
                Event e(EventCommandExec, c);
                void *res = e.process();
                delete msg;
                return res;
            }
            return NULL;
        }
    }
    return NULL;
}
Example #6
0
AST *frontend(char *txt, u32 txtlen)
{
	char *s = NULL;
	u32 *code = NULL;
	u32 i = 0;
	u32 slen;
	int tokcur, tokexp = TOK_GAME_TITLE;
	AST *tree = (AST*) malloc(sizeof(AST));

	memset(tree, 0, sizeof(AST));

	// Text MUST contain a new line char at the end
	if (txt[txtlen - 1] != '\n') {
		txt = (char*) realloc(txt, ++txtlen);
		txt[txtlen - 1] = '\n';
	}

	printf("*** Compiler front end ***\n");
	printf("Parsing...\n");

	/*** Scanner ***/
	while (i < txtlen) {
		slen = indexOfChr(&txt[i], '\n');

		if (!_isEmptyStr(&txt[i], slen)) {
			s = &txt[i];
			s[slen] = NUL;
			/*** Screener ***/
			remCmtFromStr(s);
			trimStr(s);

			if (strlen(s) > 0) {
				/*** Parser ***/
				tokcur = getToken(s);

				if (!(tokexp & tokcur)) {
					fprintf(stderr, "ERROR(%i): '%s' : ", nline, s);
					if (tokexp & TOK_CHEAT_DESC) {
						fprintf(stderr, "Cheat description expected\n");
						tokexp = TOK_ALL;
					} else /* if (tokexp & TOK_GAME_TITLE) */ {
						fprintf(stderr, "Game title expected\n");
						tokexp = TOK_GAME_TITLE | TOK_CHEAT_DESC;
					}
					nerr++;
				} else switch (tokcur) {
					case TOK_GAME_TITLE:
						s = getGameTitle(s);
						if (*s == NUL) {
							fprintf(stderr, "ERROR(%i): Empty game title\n", nline);
							nerr++;
						} else {
							checkStr(s);
							if (!nerr && addGameToTree(tree, s) < 0) {
								fprintf(stderr, "ERROR(%i): '%s' : Cannot add more games\n", nline, s);
								nerr++;
							}
						}
						tokexp = TOK_GAME_TITLE | TOK_CHEAT_DESC;
						break;

					case TOK_CHEAT_DESC:
						checkStr(s);
						if (!nerr && addCheatToTree(tree, s) < 0) {
							fprintf(stderr, "ERROR(%i): '%s' : Cannot add more cheats\n", nline, s);
							nerr++;
						}
						tokexp = TOK_ALL;
						break;

					case TOK_CHEAT_CODE:
						code = getCheatCode(s);
						if (!nerr && addCodeToTree(tree, code) < 0) {
							fprintf(stderr, "ERROR(%i): %08X %08X : Cannot add more codes\n", nline, code[0], code[1]);
							nerr++;
						}
						tokexp = TOK_ALL;
						break;
				}
			}
		}
		nline++;
		i += slen + 1;
	}

	printf("Parsing done: %i error(s), %i warning(s)\n", nerr, nwarn);

	if (nerr) {
		fprintf(stderr, "Error(s) occurred during parsing.\n");
		freeTree(tree);
		return NULL;
	} else if (!tree->ngames) {
		fprintf(stderr, "Nothing parsed.\n");
		freeTree(tree);
		return NULL;
	}

	printf("Stats: %u game(s), %u cheat(s), %u code(s)\n", tree->ngames, tree->nallcheats, tree->nallcodes);

	return tree;
}
Example #7
0
CubeMap * SceneParser::parseCubeMap()
{
	char token[MAX_PARSER_TOKEN_LENGTH];
	getToken(token);
	return new CubeMap(token);
}
Example #8
0
static struct parseNode *getParseTreeClass(struct parserState *ps)
{
    int y;
    char *name,*baseName=NULL;
    y=getToken(ps);
    if(y==NoMoreToken)
        return NULL;
    if(strcmp(ps->token,"class")!=0)
    {
        error("Error! OOPS only supports classes. Unexpected token %s at %d\n",
              ps->token,ps->lineno);
        return NULL;
    }
    struct parseNode *result,*next,*ptr,*cc;
    result=newNode(1);
    result->lineno=ps->lineno;
    y=getToken(ps);
    if(y==NoMoreToken || y!=NameToken)
    {
        error("Error! Class name expected at line %d\n",ps->lineno);
        return NULL;
    }
    name=copystr(ps->token);

    next=newNode(3);
    next->lineno=ps->lineno;

    cc=newNode(0);
    next->dat.n=cc;
    cc->lineno=ps->lineno;
    cc->dat.s=name;

    result->dat.n=next;
    ptr=next;
    y=getToken(ps);
    if(y!=NoMoreToken && strcmp(ps->token,":")==0)
    {
        y=getToken(ps);
        if(y!=NameToken)
        {
            error("Error! Base class name expected at line %d\n",ps->lineno);
            return result;
        }
        baseName=copystr(ps->token);

        cc=newNode(0);
        cc->lineno=ps->lineno;
        cc->dat.s=baseName;
        next->dat.n->next=cc;

        y=getToken(ps);
    }
    if(y!=NoMoreToken && strcmp(ps->token,"{")==0)
    {
        y=getToken(ps);
        if(y!=NameToken && strcmp(ps->token,"}")!=0)
        {
            error("Error! Method or variable definition expected at %d\n",ps->lineno);
            return result;
        }
        next=getParseTreeVar(ps);
        state=NameToken;
        while(next!=NULL)
        {
            ptr->next=next;
            ptr=next;
            ptr->next=NULL;
            if(errorOccured)
            {
                return result;
            }
            next=getParseTreeVar(ps);
        }

        if(strcmp(ps->token,"}")!=0)
        {
            if(state==NoMoreToken)
                error("Error! Missing right brace } at line %d\n",ps->lineno);
            else if(state!=NameToken)
                error("Error! Method or variable definition expected at %d\n",ps->lineno);
        }
    }
    else
    {
        error("Error! Left brace { expected at line %d\n",ps->lineno);
        return result;
    }
    return result;
}
void llvm_initialize_backend(void) {
  // Initialize LLVM options.
  std::vector<const char*> Args;
  Args.push_back(progname); // program name

  // Allow targets to specify PIC options and other stuff to the corresponding
  // LLVM backends.
#ifdef LLVM_SET_TARGET_OPTIONS
  LLVM_SET_TARGET_OPTIONS(Args);
#endif
  
  if (time_report)
    Args.push_back("--time-passes");
  if (fast_math_flags_set_p())
    Args.push_back("--enable-unsafe-fp-math");
  if (!flag_omit_frame_pointer)
    Args.push_back("--disable-fp-elim");
  if (!flag_zero_initialized_in_bss)
    Args.push_back("--nozero-initialized-in-bss");
  if (flag_debug_asm)
    Args.push_back("--asm-verbose");
  if (flag_debug_pass_structure)
    Args.push_back("--debug-pass=Structure");
  if (flag_debug_pass_arguments)
    Args.push_back("--debug-pass=Arguments");
  if (flag_exceptions)
    Args.push_back("--enable-eh");

  // If there are options that should be passed through to the LLVM backend
  // directly from the command line, do so now.  This is mainly for debugging
  // purposes, and shouldn't really be for general use.
  std::vector<std::string> ArgStrings;
  if (llvm_optns) {
    std::string Opts = llvm_optns;
    for (std::string Opt = getToken(Opts); !Opt.empty(); Opt = getToken(Opts))
      ArgStrings.push_back(Opt);
  }
  for (unsigned i = 0, e = ArgStrings.size(); i != e; ++i)
    Args.push_back(ArgStrings[i].c_str());
  Args.push_back(0);  // Null terminator.
  
  int pseudo_argc = Args.size()-1;
  cl::ParseCommandLineOptions(pseudo_argc, (char**)&Args[0]);

  TheModule = new Module("");

  // If the target wants to override the architecture, e.g. turning
  // powerpc-darwin-... into powerpc64-darwin-... when -m64 is enabled, do so
  // now.
  std::string TargetTriple = TARGET_NAME;
#ifdef LLVM_OVERRIDE_TARGET_ARCH
  std::string Arch = LLVM_OVERRIDE_TARGET_ARCH();
  if (!Arch.empty()) {
    std::string::size_type DashPos = TargetTriple.find('-');
    if (DashPos != std::string::npos)// If we have a sane t-t, replace the arch.
      TargetTriple = Arch + TargetTriple.substr(DashPos);
  }
#endif
  TheModule->setTargetTriple(TargetTriple);
  
  TheTypeConverter = new TypeConverter();
  
  // Create the TargetMachine we will be generating code with.
  // FIXME: Figure out how to select the target and pass down subtarget info.
  std::string Err;
  const TargetMachineRegistry::Entry *TME = 
    TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Err);
  if (!TME) {
    cerr << "Did not get a target machine!\n";
    exit(1);
  }

  // Figure out the subtarget feature string we pass to the target.
  std::string FeatureStr;
  // The target can set LLVM_SET_SUBTARGET_FEATURES to configure the LLVM
  // backend.
#ifdef LLVM_SET_SUBTARGET_FEATURES
  SubtargetFeatures Features;
  LLVM_SET_SUBTARGET_FEATURES(Features);
  FeatureStr = Features.getString();
#endif
  TheTarget = TME->CtorFn(*TheModule, FeatureStr);

  // Install information about target datalayout stuff into the module for
  // optimizer use.
  TheModule->setDataLayout(TheTarget->getTargetData()->
                           getStringRepresentation());
  
  if (optimize) {
    RegisterScheduler::setDefault(createDefaultScheduler);
  } else {
    RegisterScheduler::setDefault(createBFS_DAGScheduler);
  }
  
  RegisterRegAlloc::setDefault(createLinearScanRegisterAllocator);
 
  if (!optimize && debug_info_level > DINFO_LEVEL_NONE)
    TheDebugInfo = new DebugInfo(TheModule);
}
Example #10
0
static struct parseNode *getParseTreeMethod(struct parserState *ps)
{
    int y=getToken(ps);
    struct parseNode *result,*next,*ptr,*type,*arg;
    result=newNode(11);
    result->lineno=ps->lineno;
    if(y==NameToken)
    {
        next=newNode(5);
        next->lineno=ps->lineno;
        result->dat.n=next;
        ptr=next;
        type=newNode(0);
        type->lineno=ps->lineno;
        type->dat.s=copystr(ps->token);
        next->dat.n=type;

        y=getToken(ps);
        if(y==NameToken)
        {
            arg=newNode(0);
            arg->lineno=ps->lineno;
            arg->dat.s=copystr(ps->token);
            type->next=arg;
            y=getToken(ps);
        }
        else
        {
            error("Error! Missing type name or argument type at %d, found %s\n",
                  ps->lineno,ps->token);
            return result;
        }

        while(y!=NoMoreToken && ps->token[0]!=')')
        {
            if(ps->token[0]!=',')
            {
                error("Error! Expected ',' or ';' before %s at %d\n",
                      ps->token,ps->lineno);
                return result;
            }
            y=getToken(ps);
            if(y!=NameToken)
            {
                error("Error! Missing type name or argument type at %d, found %s\n",
                      ps->lineno,ps->token);
                return result;
            }
            next=newNode(5);
            next->lineno=ps->lineno;
            ptr->next=next;
            ptr=next;
            type=newNode(0);
            type->lineno=ps->lineno;
            type->dat.s=copystr(ps->token);
            next->dat.n=type;

            y=getToken(ps);
            if(y==NameToken)
            {
                arg=newNode(0);
                arg->lineno=ps->lineno;
                arg->dat.s=copystr(ps->token);
                type->next=arg;
            }
            else
            {
                error("Error! Missing type name or argument type at %d, found %s\n",
                      ps->lineno,ps->token);
                return result;
            }
            y=getToken(ps);
        }
    }
    y=getToken(ps);
    if(ps->token[0]!='{')
    {
        error("Error! Left bracket { expected at %d, found %s\n"
              ,ps->lineno,ps->token);
        return result;
    }
    result->next=getParseTreeBlock(ps,2);
    result->next->dat.n=repairPTStmt(result->next->dat.n);
    state=getToken(ps);
    return result;
}
Example #11
0
static struct parseNode *getParseTreeVar(struct parserState *ps)
{
    struct parseNode *result=NULL,*next,*ptr;
    int y;
    char *name;
    if(ps->token[0]=='}' || ps->token[0]==0)
        return NULL;
    name=copystr(ps->token);
    result=newNode(9);
    result->lineno=ps->lineno;

    next=newNode(0);
    next->lineno=ps->lineno;
    next->dat.s=name;
    result->dat.n=next;
    ptr=next;
    y=getToken(ps);
    if(y!=NameToken && ps->token[0]!='(')
    {
        state=y;
        error("Error! Method or variable name expected at %d, found %s\n"
              ,ps->lineno,ps->token);
        return result;
    }
    if(y==NameToken)
    {
        result->type=7;
        name=copystr(ps->token);
        next=newNode(0);
        next->lineno=ps->lineno;
        next->dat.s=name;
        ptr->next=next;
        ptr=next;
        y=getToken(ps);
    }
    if(ps->token[0]=='(')
    {
        ptr->next=getParseTreeMethod(ps);
    }
    else
    {
        result->type=5;
        while(ps->token[0]==',')
        {
            y=getToken(ps);
            if(y!=NameToken)
            {
                error("Error! Variable name expected at %d, found %s\n"
                      ,ps->lineno,ps->token);
                return result;
            }
            name=copystr(ps->token);
            next=newNode(0);
            next->lineno=ps->lineno;
            next->dat.s=name;
            ptr->next=next;
            ptr=next;
            y=getToken(ps);
        }
        if(ps->token[0]!=';')
        {
            error("Error! Semicolon ; expected at %d\n",ps->lineno);
            return result;
        }
        y=getToken(ps);
        state=y;
    }
    return result;
}
Example #12
0
static void parse( Translator *tor )
{
    QString text;
    QString com;
    QString extracomment;

    yyCh = getChar();

    yyTok = getToken();
    while ( yyTok != Tok_Eof ) {
        switch ( yyTok ) {
        case Tok_class:
            yyTok = getToken();
            if(yyTok == Tok_Ident) {
                yyScope.push(new Scope(yyIdent, Scope::Clazz, yyLineNo));
            }
            else {
                yyMsg() << qPrintable(LU::tr("'class' must be followed by a class name.\n"));
                break;
            }
            while (!match(Tok_LeftBrace)) {
                yyTok = getToken();
            }
            break;

        case Tok_tr:
            yyTok = getToken();
            if ( match(Tok_LeftParen) && matchString(text) ) {
                com.clear();
                bool plural = false;

                if ( match(Tok_RightParen) ) {
                    // no comment
                } else if (match(Tok_Comma) && matchStringOrNull(com)) {   //comment
                    if ( match(Tok_RightParen)) {
                        // ok,
                    } else if (match(Tok_Comma)) {
                        plural = true;
                    }
                }
                if (!text.isEmpty())
                    recordMessage(tor, context(), text, com, extracomment, plural);
            }
            break;
        case Tok_translate:
            {
                QString contextOverride;
                yyTok = getToken();
                if ( match(Tok_LeftParen) &&
                     matchString(contextOverride) &&
                     match(Tok_Comma) &&
                     matchString(text) ) {

                    com.clear();
                    bool plural = false;
                    if (!match(Tok_RightParen)) {
                        // look for comment
                        if ( match(Tok_Comma) && matchStringOrNull(com)) {
                            if (!match(Tok_RightParen)) {
                                if (match(Tok_Comma) && matchExpression() && match(Tok_RightParen)) {
                                    plural = true;
                                } else {
                                    break;
                                }
                            }
                        } else {
                            break;
                        }
                    }
                    if (!text.isEmpty())
                        recordMessage(tor, contextOverride, text, com, extracomment, plural);
                }
            }
            break;

        case Tok_Ident:
            yyTok = getToken();
            break;

        case Tok_Comment:
            if (yyComment.startsWith(QLatin1Char(':'))) {
                yyComment.remove(0, 1);
                extracomment.append(yyComment);
            }
            yyTok = getToken();
            break;

        case Tok_RightBrace:
            if ( yyScope.isEmpty() ) {
                yyMsg() << qPrintable(LU::tr("Excess closing brace.\n"));
            }
            else
                delete (yyScope.pop());
            extracomment.clear();
            yyTok = getToken();
            break;

         case Tok_LeftBrace:
            yyScope.push(new Scope(QString(), Scope::Other, yyLineNo));
            yyTok = getToken();
            break;

        case Tok_Semicolon:
            extracomment.clear();
            yyTok = getToken();
            break;

        case Tok_Package:
            yyTok = getToken();
            while(!match(Tok_Semicolon)) {
                switch(yyTok) {
                    case Tok_Ident:
                        yyPackage.append(yyIdent);
                        break;
                    case Tok_Dot:
                        yyPackage.append(QLatin1String("."));
                        break;
                    default:
                         yyMsg() << qPrintable(LU::tr("'package' must be followed by package name.\n"));
                         break;
                }
                yyTok = getToken();
            }
            break;

        default:
            yyTok = getToken();
        }
    }

    if ( !yyScope.isEmpty() )
        yyMsg(yyScope.top()->line) << qPrintable(LU::tr("Unbalanced opening brace.\n"));
    else if ( yyParenDepth != 0 )
        yyMsg(yyParenLineNo) << qPrintable(LU::tr("Unbalanced opening parenthesis.\n"));
}
Example #13
0
bool MacroExpander::collectMacroArgs(const Macro &macro,
                                     const Token &identifier,
                                     std::vector<MacroArg> *args)
{
    Token token;
    getToken(&token);
    assert(token.type == '(');

    args->push_back(MacroArg());
    for (int openParens = 1; openParens != 0; )
    {
        getToken(&token);

        if (token.type == Token::LAST)
        {
            mDiagnostics->report(Diagnostics::PP_MACRO_UNTERMINATED_INVOCATION,
                                 identifier.location, identifier.text);
            // Do not lose EOF token.
            ungetToken(token);
            return false;
        }

        bool isArg = false; // True if token is part of the current argument.
        switch (token.type)
        {
          case '(':
            ++openParens;
            isArg = true;
            break;
          case ')':
            --openParens;
            isArg = openParens != 0;
            break;
          case ',':
            // The individual arguments are separated by comma tokens, but
            // the comma tokens between matching inner parentheses do not
            // seperate arguments.
            if (openParens == 1)
                args->push_back(MacroArg());
            isArg = openParens != 1;
            break;
          default:
            isArg = true;
            break;
        }
        if (isArg)
        {
            MacroArg &arg = args->back();
            // Initial whitespace is not part of the argument.
            if (arg.empty())
                token.setHasLeadingSpace(false);
            arg.push_back(token);
        }
    }

    const Macro::Parameters &params = macro.parameters;
    // If there is only one empty argument, it is equivalent to no argument.
    if (params.empty() && (args->size() == 1) && args->front().empty())
    {
        args->clear();
    }
    // Validate the number of arguments.
    if (args->size() != params.size())
    {
        Diagnostics::ID id = args->size() < macro.parameters.size() ?
            Diagnostics::PP_MACRO_TOO_FEW_ARGS :
            Diagnostics::PP_MACRO_TOO_MANY_ARGS;
        mDiagnostics->report(id, identifier.location, identifier.text);
        return false;
    }

    // Pre-expand each argument before substitution.
    // This step expands each argument individually before they are
    // inserted into the macro body.
    for (std::size_t i = 0; i < args->size(); ++i)
    {
        MacroArg &arg = args->at(i);
        TokenLexer lexer(&arg);
        MacroExpander expander(&lexer, mMacroSet, mDiagnostics);

        arg.clear();
        expander.lex(&token);
        while (token.type != Token::LAST)
        {
            arg.push_back(token);
            expander.lex(&token);
        }
    }
    return true;
}
bool GraphDog::command(const std::vector<CommandParam>& params)
{
	string udid=getUdid();
    string email=getEmail();
    string auid=getAuID();
    string token;
	//저장되어있는 토큰불러오기. 없으면 생성
    token=getToken();
	
	int insertIndex = AutoIncrease::get();
	std::vector<CommandType> cmdCollect;
	CommandsType cmdQueue;
	// cmdQueue 에 명령 추가하고...
	JsonBox::Object jsonTotalCmd;
	cmdQueue.chunk = GDStruct((char*)malloc(1), 0, CURLE_AGAIN);
	int i=0;
	for(std::vector<CommandParam>::const_iterator iter = params.begin(); iter != params.end(); ++iter, i++)
	{
		ostringstream oss;
		oss << (iter->param);
		
		char buf[20];
		sprintf(buf, "%d", i);
		JsonBox::Object param;
		param["p"] = iter->param;
		param["a"] = iter->action;
		jsonTotalCmd[buf] = param; // dict 로
		CommandType cmd = {iter->target, iter->selector, oss.str(), iter->action};
		cmdQueue.commands[buf] = cmd;
		cmdCollect.push_back(cmd);
	}
	ostringstream oss2;
	oss2 << jsonTotalCmd;
	cmdQueue.commandStr = oss2.str();
	cmdQueue.caller = this;
	commandQueue[insertIndex] = cmdQueue;
	pthread_t p_thread;
	int thr_id;
	
	// 쓰레드 생성 아규먼트로 1 을 넘긴다.
	thr_id = pthread_create(&p_thread, NULL, t_function, (void*)insertIndex);
	if (thr_id < 0)
	{
		//쓰레드생성오류시
		JsonBox::Object resultobj;
		resultobj["state"]= JsonBox::Value("error");
		resultobj["errorMsg"]=JsonBox::Value("don't create thread");
		resultobj["errorCode"]=JsonBox::Value(1001);
		
		for(std::vector<CommandType>::const_iterator iter = cmdCollect.begin(); iter != cmdCollect.end(); ++iter)
		{
			if( iter->target != 0 && iter->selector != 0)
				((iter->target)->*(iter->selector))(resultobj);	
		}
		
		if( cmdQueue.chunk.memory )
			free(cmdQueue.chunk.memory);
		commandQueue.erase(insertIndex);
		return false;
	}
	
    return true;
}
Example #15
0
void block()
{
    int varCount = 0;
    //constant symbol function
    if (token.sym ==  constsym)
    {
        do
        {
            getToken();
            if(token.sym != identsym)
                getError(1);
            strcpy(symbolHolder.name, token.word);
             getToken();
            if(token.sym != eqlsym)
                getError(2);
            getToken();
            if(token.sym != numbersym)
                getError(3);
            enter(cons, symbolHolder.name, 0, 0, token.value);
            getToken();
        }
        while (token.sym == commasym);

        if(token.sym != semicolonsym)
            getError(4);
        getToken();
    }
    //variable symbol function
    if(token.sym == varsym)
    {
        do
        {

           getToken();
           if(token.sym != identsym)
                getError(1);
            enter(var, token.word, 0, 4 + varCount, 0);
            varCount ++;
           getToken();
        }
        while(token.sym == commasym);
        if(token.sym != semicolonsym)
            getError(4);
        getToken();
    }
    if(token.sym == procsym)
    {
        do
        {
            getToken();
            if(token.sym != identsym)
                getError(1);
            enter(proc, token.word, 0, codeSpot, token.sym);
            getToken();
            if(token.sym != semicolonsym)
                getError(4);
            getToken();
            block();
            if(token.sym != semicolonsym)
                getError(4);
            getToken();
        }
        while(token.sym == procsym);
    }
    statement(varCount);
}
Example #16
0
static void a3d_textbox_reflow(a3d_widget_t* widget,
                               float w, float h)
{
	assert(widget);
	LOGD("debug w=%f, h=%f", w, h);

	a3d_textbox_t* self = (a3d_textbox_t*) widget;

	// reflow text when changes occur
	if((self->dirty  == 0) &&
	   (self->last_w == w) &&
	   (self->last_h == h))
	{
		return;
	}
	self->dirty  = 0;
	self->last_w = w;
	self->last_h = h;

	// determine maxi
	a3d_font_t* font   = a3d_screen_font(widget->screen);
	float       aspect = a3d_font_aspectRatio(font);
	float       size   = a3d_screen_layoutText(widget->screen,
	                                           self->style_text);
	int         maxi   = (int) (w/(aspect*size)) - 1;

	// maxi does not include null character
	// but max_len does
	// limit to max_len
	if((maxi >= self->max_len) ||
	   (maxi == 0))
	{
		maxi = self->max_len - 1;
	}

	// clear the text
	a3d_listbox_t*  listbox = (a3d_listbox_t*) self;
	a3d_listitem_t* iter    = a3d_list_head(listbox->list);
	while(iter)
	{
		a3d_text_t* text;
		text = (a3d_text_t*) a3d_list_remove(listbox->list, &iter);
		a3d_text_delete(&text);
	}

	// initialize parser
	char tok[256];
	char dst[256];
	int  srci = 0;
	int  toki = 0;
	int  dsti = 0;
	int  type = A3D_TOKEN_END;

	// reflow the string(s)
	iter = a3d_list_head(self->strings);
	while(iter)
	{
		const char* src = (const char*) a3d_list_peekitem(iter);

		srci = 0;
		type = getToken(src, tok, &srci, &toki);
		while(type != A3D_TOKEN_END)
		{
			if(type == A3D_TOKEN_BREAK)
			{
				if(dsti > 0)
				{
					a3d_textbox_printText(self, dst);
					a3d_textbox_printText(self, "");
				}
				else
				{
					a3d_textbox_printText(self, "");
				}
				dsti = 0;
				break;
			}

			if(dsti == 0)
			{
				strncpy(dst, tok, 256);
				dst[255] = '\0';
				dsti = toki;
			}
			else
			{
				if(dsti + toki + 1 <= maxi)
				{
					strcat(dst, " ");
					strcat(dst, tok);
					dst[255] = '\0';
					dsti += toki + 1;
				}
				else
				{
					a3d_textbox_printText(self, dst);

					strncpy(dst, tok, 256);
					dst[255] = '\0';
					dsti = toki;
				}
			}

			type = getToken(src, tok, &srci, &toki);
		}

		iter = a3d_list_next(iter);
	}

	if(dsti > 0)
	{
		a3d_textbox_printText(self, dst);
	}
}
Example #17
0
void statement(int varCount)
{
    int changeSpot = 0;
    int sym;
    symbol localSymbolHolder;
    int localVarCount = varCount;
    if(token.sym == identsym)
    {
        //printf("\n\nThe token word is : %s\n\n", token.word);
        //printf("The symbol word is : %s\n", symbol_table[1].name);
        if(isSymbol(token.word))
            localSymbolHolder = symbol_table[getSymbol(token.word)];
        else
            getError(11);
        getToken();
    if(token.sym != becomessym)
        getError(5);
    getToken();
    expression();
    enter(var,localSymbolHolder.name,0,0,getTop());
    emit(4, 0, localSymbolHolder.addr);
   // printf("\n\nThe TOS IS %d\n\n", getTop());
    }
    else if(token.sym == callsym)
    {
        getToken();
        if(token.sym != identsym)
            getError(2);
        getToken();
    }
    else if(token.sym == beginsym)
    {
        emit(6, 0, 4 + localVarCount);
        getToken();
        statement(localVarCount);
        while(token.sym == semicolonsym)
        {
            getToken();
            statement(localVarCount);
        }
        if(token.sym != endsym)
             getError(6);
        getToken();
    }
    else if(token.sym == ifsym)
    {
        getToken();
        changeSpot = condition();
        if(token.sym != thensym)
            getError(6);
        getToken();
        statement(localVarCount);
    }
    else if(token.sym == whilesym)
    {
        getToken();
        condition();
        if(token.sym != dosym)
            getError(7);
        getToken();
        statement(localVarCount);
    }
   // printf("\n\nThe change spot and codespot  is: %d, %d\n\n", changeSpot, codeSpot);
    if(changeSpot != 0)
        code3[(changeSpot * 3) + 2] =codeSpot;
}
Example #18
0
IconCfg::IconCfg(QWidget *parent, IconsPlugin *plugin)
        : IconCfgBase(parent)
{
    m_plugin = plugin;
    unsigned i;
    for (i = 1; ; i++){
        const char *n = plugin->getIconDLLs(i);
        if ((n == NULL) || (*n == 0)) break;
        string v = n;
        IconsDef d;
        d.protocol = getToken(v, ',');
        d.icon = v;
        d.index = -1;
        defs.push_back(d);
    }

    list<string> icons;
    Event e(EventGetIcons, &icons);
    e.process();

    list<string> protocols;
    for (list<string>::iterator it = icons.begin(); it != icons.end(); ++it){
        string name = (*it);
        int n = name.find('_');
        char c = name[0];
        if ((c < 'A') || (c > 'Z'))
            continue;
        if (n <= 0)
            continue;
        name = name.substr(0, n);
        list<string>::iterator its;
        for (its = protocols.begin(); its != protocols.end(); ++its)
            if ((*its) == name)
                break;
        if (its != protocols.end())
            continue;
        protocols.push_back(name);
    }
    i = 0;
    for (list<string>::iterator its = protocols.begin(); its != protocols.end(); ++its, i++){
        cmbProtocol->insertItem(i18n((*its).c_str()));
        list<IconsDef>::iterator it;
        for (it = defs.begin(); it != defs.end(); ++it){
            if ((*it).protocol == (*its)){
                (*it).index = i;
                break;
            }
        }
        if (it == defs.end()){
            IconsDef d;
            d.protocol = (*its);
            d.index = i;
            defs.push_back(d);
        }
    }
    connect(cmbProtocol, SIGNAL(activated(int)), this, SLOT(protocolChanged(int)));
    cmbProtocol->setCurrentItem(0);
    protocolChanged(0);
    lblMore->setUrl("http://miranda-im.org/download/index.php?action=display&id=35");
#ifdef WIN32
    edtIcon->setStartDir(QFile::decodeName(app_file("icons/").c_str()));
#else
    edtIcon->setStartDir(QFile::decodeName(user_file("icons/").c_str()));
#endif
    edtIcon->setTitle(i18n("Select icons DLL"));
    edtIcon->setFilePreview(createPreview);
#ifdef USE_KDE
    edtIcon->setFilter(i18n("*.dll|Icons themes"));
#else
    edtIcon->setFilter(i18n("Icons themes (*.dll)"));
#endif
    lblMore->setText(i18n("Get more icons themes"));
    connect(edtIcon, SIGNAL(textChanged(const QString&)), this, SLOT(textChanged(const QString&)));
    for (QObject *p = parent; p != NULL; p = p->parent()){
        if (!p->inherits("QTabWidget"))
            continue;
        QTabWidget *tab = static_cast<QTabWidget*>(p);
        m_smiles = new SmileCfg(tab, plugin);
        tab->addTab(m_smiles, i18n("Smiles"));
        tab->adjustSize();
        break;
    }
}
Example #19
0
bool parserCls::doStmt(void){
 bool bb1=true,bb2=true,foundControlVar=false;
 tokenContainCls tcs1=getCurToken();exprContainCls *ce0,*ce1,*ce2,*ce3;
 int a1=noSourceLine,a2=0,a3=0;
  EtokenType tt2 ;
 EinstructionWord tt1 =ErrorInstr;
 getToken();
 noLoop ++ ;
 switch(getTokenType()){
	case While :
		tt1 = DoWhileInstr;
		bb1 = exprShould(tt1) ;
	break ;
	case Until:
		tt1=DoUntilInstr;
		bb1=exprShould(tt1);
	break ;
	case ForEver:
		tt1=DoForEverInstr ;
		getToken();
	break ;
	case For:
		tt1=DoForInstr;
		bb1 = exprShould(tt1) ;
	break ;
	case Semicolon :
	case EndOfLine :
	  tt1 = DoInstr ;
	  noLoop --;
	break ;
	default:
		tt1=DoToInstr;
		tt2=getTokenType();
	  tokenContainCls   tcs2=getCurToken() ;
	  if((tt2==Array)||(tt2==Name))
	  {
		 addControlVar(tcs2 );foundControlVar=true;
		 ce0=new exprContainCls(1);ce0->push(tcs2);getToken();
		 if(getTokenType() == Eq)
		  {
			bb2 = exprShould(DoToInstr);
			ce1 = getNewExpr();
		  }
		 else
		  {
			 bb2= false ;
			 errorDo(1, tcs1,  tcs2 );
			 foundControlVar=false;
			 popControlVar();
		  }
	  }
	  else
	  {
		 errorDo(2,tcs1,tcs2);
		 bb2=false;
	  }
	  if(bb2)
		if(getTokenType() == To )
		 {
			bb2 = exprShould(DoToInstr);
			ce2 =  getNewExpr();
		 }
		 else
		 {
			errorDo(2 , tcs1 , tcs2 ) ;
			bb2 = false ;
		 }
	  if(bb2)
		if(getTokenType() == By)
		{
		  bb2=exprShould(DoToByInstr);
		  tt1=DoToByInstr;
		  ce3=getNewExpr();
		}
 }
 if((tt1 == DoWhileInstr) || (tt1 == DoForInstr)||(tt1 == DoUntilInstr) )
	ce0=getNewExpr();
 bb1 = bb1 && bb2 ;  bool bb3=true ;
 if(bb1)   endWhiteLine();
 else      bb3 = syncStmtError();
 if(!bb3)  return false ;
 compoundStmt(tcs1,a2 ) ;/// if error not found show the error
 a3 = stmtNo ;
 if(foundControlVar) popControlVar();
 noLoop--; initEiwCss(tt1) ;
 if((tt1==DoWhileInstr)||(tt1==DoUntilInstr)||(tt1==DoForInstr))
	addExprToStmt(ce0,0);
 else if((tt1 == DoInstr)||(tt1==DoForEverInstr))
  {if(tt1 == DoInstr )	 noLoop ++ ;}
 else if( (tt1 == DoToInstr ) || (tt1 == DoToByInstr) )
 {addExprToStmt(ce0,0); addExprToStmt(ce1,1);addExprToStmt(ce2,2);
  if(tt1 == DoToByInstr ) addExprToStmt(ce3,3);
 }
 valInt[0] = a1 ;valInt[1] = a2 -1;valInt[2] = a3;noOfValInt=3;
 return bb1  ;
}
Example #20
0
void FetchThread::run()
{
    string headers;
    DWORD flags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_UI | INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_COOKIES;
    if (!m_client->m_bRedirect)
        flags |= INTERNET_FLAG_NO_AUTO_REDIRECT;
    const char *verb = "GET";
    unsigned postSize = m_client->m_client->post_size();
    if (postSize != NO_POSTSIZE)
        verb = "POST";
    URL_COMPONENTSA url;
    memset(&url, 0, sizeof(url));
    url.dwStructSize = sizeof(url);
    char host[256];
    url.lpszHostName      = host;
    url.dwHostNameLength  = sizeof(host);
    char user[256];
    url.lpszUserName      = user;
    url.dwUserNameLength  = sizeof(user);
    char pass[256];
    url.lpszPassword	  = pass;
    url.dwPasswordLength  = sizeof(pass);
    char urlPath[1024];
    url.lpszUrlPath		  = urlPath;
    url.dwUrlPathLength   = sizeof(urlPath);
    char extra[1024];
    url.lpszExtraInfo	  = extra;
    url.dwExtraInfoLength = sizeof(extra);
    if (!_InternetCrackUrl(m_client->m_uri.c_str(), 0, ICU_DECODE, &url)){
        error("InternetCrackUrl");
        return;
    }
    if (url.nScheme == INTERNET_SCHEME_HTTPS){
        flags |= INTERNET_FLAG_SECURE;
    }else if (url.nScheme != INTERNET_SCHEME_HTTP){
        error("Unsupported scheme");
        return;
    }
    hCon = _InternetConnect(hInet, url.lpszHostName, url.nPort,
                            url.lpszUserName, url.lpszPassword, INTERNET_SERVICE_HTTP, 0, 0);
    if (hCon == NULL){
        error("InternetConnect");
        return;
    }
    string uri = url.lpszUrlPath;
    if (url.lpszExtraInfo)
        uri += url.lpszExtraInfo;
    hReq = _HttpOpenRequest(hCon, verb, uri.c_str(), NULL, NULL, NULL, flags, 0);
    if (hReq == NULL){
        error("HttpOpenRequest error");
        return;
    }
    for (HEADERS_MAP::iterator it = m_client->m_hOut.begin(); it != m_client->m_hOut.end(); ++it){
        string name = (*it).first.c_str();
        if (!headers.empty())
            headers += "\r\n";
        headers += name;
        headers += ": ";
        headers += (*it).second.c_str();
    }
    Buffer b;
    b.packetStart();
    b << verb << " " << uri.c_str() << " HTTP/1.0\r\n" << headers.c_str() << "\r\n";
    log_packet(b, true, HTTPPacket);
    for (;;){
        if (postSize != NO_POSTSIZE){
            INTERNET_BUFFERSA BufferIn;
            memset(&BufferIn, 0, sizeof(BufferIn));
            BufferIn.dwStructSize    = sizeof(INTERNET_BUFFERSA);
            BufferIn.lpcszHeader     = headers.c_str();
            BufferIn.dwHeadersLength = headers.length();
            BufferIn.dwHeadersTotal  = headers.length();
            BufferIn.dwBufferTotal   = (postSize != NO_POSTSIZE) ? postSize : 0;
            if (!_HttpSendRequestEx(hReq, &BufferIn, NULL, HSR_INITIATE | HSR_SYNC, 0)){
                error("HttpSendRequestEx");
                return;
            }
            unsigned size = postSize;
            while (size){
                char buff[4096];
                unsigned tail = size;
                if (tail > sizeof(buff))
                    tail = sizeof(buff);
                const char *data = m_client->m_client->read_data(buff, tail);
                if (data == NULL){
                    error("ReadStreamError");
                    return;
                }
                DWORD res;
                if (m_bClose)
                    return;
                if (!_InternetWriteFile(hReq, (void*)data, tail, &res)){
                    error("InternetWriteFile");
                    return;
                }
                if (m_client->m_speed){
                    m_client->m_sendSize += tail;
                    time_t now;
                    time(&now);
                    if ((unsigned)now != m_client->m_sendTime){
                        m_client->m_sendTime = now;
                        m_client->m_sendSize = 0;
                    }
                    if (m_client->m_sendSize > (m_client->m_speed << 18)){
                        Sleep(1000);
                        return;
                    }
                }
                size -= tail;
            }
            if (m_bClose)
                return;
            if(!_HttpEndRequest(hReq, NULL, 0, 0)){
                error("HttpEndRequest");
                return;
            }
        }else{
            if (!_HttpSendRequest(hReq, headers.c_str(), headers.length(), NULL, 0)){
                error("HttpSendRequest");
                return;
            }
        }
        DWORD dwCode;
        DWORD dwSize = sizeof(dwCode);
        _HttpQueryInfo (hReq, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwCode, &dwSize, NULL);
        if (dwCode != HTTP_STATUS_PROXY_AUTH_REQ)
            break;
        DWORD res = _InternetErrorDlg (GetDesktopWindow(),
                                       hReq, ERROR_INTERNET_INCORRECT_PASSWORD,
                                       FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
                                       FLAGS_ERROR_UI_FLAGS_GENERATE_DATA |
                                       FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS, NULL);
        if (res != ERROR_INTERNET_FORCE_RETRY)
            break;
    }

    DWORD size = 0;
    DWORD err  = 0;
    _HttpQueryInfo(hReq, HTTP_QUERY_RAW_HEADERS_CRLF, NULL, &size, 0);
    err = GetLastError();
    if (err != ERROR_INSUFFICIENT_BUFFER ){
        error("HttpQueryInfo");
        return;
    }
    Buffer in_headers;
    in_headers.packetStart();
    in_headers.init(size);
    if (!_HttpQueryInfo(hReq, HTTP_QUERY_RAW_HEADERS_CRLF, in_headers.data(), &size, 0)){
        error("HttpQueryInfo");
        return;
    }
    in_headers.setWritePos(size);
    log_packet(in_headers, false, HTTPPacket);
    string line;
    bool bFirst = true;
    for (; in_headers.readPos() < in_headers.writePos(); ){
        if (!in_headers.scan("\r\n", line)){
            line = "";
            unsigned size = in_headers.writePos() - in_headers.readPos();
            line.append(size, '\x00');
            in_headers.unpack((char*)line.c_str(), size);
        }
        if (bFirst){
            bFirst = false;
            getToken(line, ' ');
            m_client->m_code = atol(line.c_str());
            continue;
        }
        m_client->m_hIn += line;
        m_client->m_hIn += '\x00';
    }
    if (bFirst){
        error("Bas answer");
        return;
    }
    for (;;){
        DWORD readn;
        char buff[4096];
        if (!_InternetReadFile(hReq, buff, sizeof(buff), &readn)){
            error("InternetReadFile");
            return;
        }
        if (m_bClose)
            return;
        if (readn == 0)
            break;
        if (!m_client->m_client->write_data(buff, readn)){
            error("Write error");
            return;
        }
    }
    /* Signals / Slots aren't thread-safe - need to use an event */
    close();
    QCustomEvent* ce = new QCustomEvent(Q_EVENT_SIM_FETCH_DONE);
    ce->setData(m_client->m_client);
    postEvent(m_client, ce);
    log(L_DEBUG,"EventPosted!");
}
Example #21
0
void FloatyWnd::paintEvent(QPaintEvent*)
{
    int w = width()  - 4;
    int h = height() - 4;

    QPixmap pict(w, h);
    QPainter p(&pict);
    p.fillRect(QRect(0, 0, width(), height()), colorGroup().base());
    PaintView pv;
    pv.p        = &p;
    pv.pos      = QPoint(2, 2);
    pv.size		= QSize(w, h);
    pv.win      = this;
    pv.isStatic = false;
    pv.height   = h;
    if (m_plugin->core->getUseSysColors()){
        p.setPen(colorGroup().text());
    }else{
        p.setPen(QColor(m_plugin->core->getColorOnline()));
    }
    Event e(EventPaintView, &pv);
    e.process();

    if (m_plugin->core->getUseSysColors()){
        if (m_status != STATUS_ONLINE)
            p.setPen(palette().disabled().text());
    }else{
        switch (m_status){
        case STATUS_ONLINE:
            break;
        case STATUS_AWAY:
            p.setPen(m_plugin->core->getColorAway());
            break;
        case STATUS_NA:
            p.setPen(m_plugin->core->getColorNA());
            break;
        case STATUS_DND:
            p.setPen(m_plugin->core->getColorDND());
            break;
        default:
            p.setPen(m_plugin->core->getColorOffline());
            break;
        }
    }

    int x = 0;
    const char *statusIcon = m_statusIcon;
    if (m_unread && m_plugin->m_bBlink){
        CommandDef *def = m_plugin->core->messageTypes.find(m_unread);
        if (def)
            statusIcon = def->icon;
    }

    if (statusIcon){
        const QPixmap &pict = Pict(statusIcon);
        x += 2;
        p.drawPixmap(x, (h - pict.height()) / 2, pict);
        x += pict.width() + 2;
    }
    QRect br;
    p.drawText(x, 0, w, h, AlignLeft | AlignVCenter, m_text, -1, &br);
    x = br.right() + 5;
    string icons = m_icons;
    while (icons.length()){
        string icon = getToken(icons, ',');
        const QPixmap &pict = Pict(icon.c_str());
        x += 2;
        p.drawPixmap(x, (h - pict.height()) / 2, pict);
        x += pict.width();
    }
    p.end();

    p.begin(this);
    p.drawPixmap(QPoint(2, 2), pict);
    p.setPen(colorGroup().dark());
    p.moveTo(1, 1);
    p.lineTo(width() - 2, 1);
    p.lineTo(width() - 2, height() - 2);
    p.lineTo(1, height() - 2);
    p.lineTo(1, 1);
    p.setPen(colorGroup().shadow());
    p.moveTo(0, height() - 1);
    p.lineTo(width() - 1, height() - 1);
    p.lineTo(width() - 1, 1);
    p.moveTo(width() - 3, 2);
    p.lineTo(2, 2);
    p.lineTo(2, height() - 3);
    p.setPen(colorGroup().light());
    p.moveTo(2, height() - 3);
    p.lineTo(width() - 3, height() - 3);
    p.lineTo(width() - 3, 2);
    p.moveTo(width() - 1, 0);
    p.lineTo(0, 0);
    p.lineTo(0, height() - 1);
}
Example #22
0
void FetchClientPrivate::_fetch(const char *headers, Buffer *postData, bool bRedirect)
{
    stop();
    m_bDone = false;
    m_data.init(0);
    m_data.packetStart();
    m_postData  = postData;
    m_bRedirect = bRedirect;
    m_postSize  = 0;
    m_sendTime	= 0;
    m_sendSize  = 0;
#ifdef WIN32
    m_thread	= NULL;
#endif
    if (headers){
        string head = headers;
        while (!head.empty()){
            string header = getToken(head, '\n');
            string key = getToken(header, ':');
            unsigned n;
            for (n = 0; n < header.length(); n++)
                if (header[n] != ' ')
                    break;
            header = header.substr(n);
            addHeader(key.c_str(), header.c_str());
        }
    }
#ifdef WIN32
    m_errCode = 0;
    if (hInet){
        m_state  = Data;
        m_thread = new FetchThread(this);
        m_thread->start();
        return;
    }
#endif
    m_received = 0;
    m_socket = new ClientSocket(this);
#ifdef USE_OPENSSL
    m_bHTTPS = false;
#endif
    string proto;
    string host;
    string user;
    string pass;
    string uri;
    string extra;
    unsigned short port;
    if (!FetchClient::crackUrl(m_uri.c_str(), proto, host, port, user, pass, uri, extra)){
        m_socket->error_state("Bad URL");
        return;
    }
    if (proto != "http"){
#ifdef USE_OPENSSL
        if (proto == "https"){
            m_bHTTPS = true;
        }else{
#endif
            log(L_WARN, "Unsupported protocol %s", m_uri.c_str());
            return;
#ifdef USE_OPENSSL
        }
#endif
    }
    log(L_DEBUG, "Start connect %s:%u", host.c_str(), port);
    m_socket->connect(host.c_str(), port, (TCPClient*)(-1));
}
Example #23
0
void RewriteToken( void )
/***********************/
{
    REWRITE *r;
    REWRITE_TOKENS *rt;
    uint_8 *stop;
    uint_32 srcfile_index;
    SRCFILE srcfile;
    uint_32 absolute;
    int code_byte;
    unsigned len;

    r = currRewrite;
    rt = r->curr;
    stop = &(rt->stream[rt->count]);
    CurToken = getToken( r, &rt, &stop );
    if( CurToken == T_REWRITE_MODS ) {
        code_byte = getByte( r, &rt, &stop );
        if( code_byte == CODE_FILE ) {
            getBinary( r, &rt, &stop, (uint_8*)&srcfile_index, sizeof( srcfile_index ) );
            srcfile = accessSrcFile( r, srcfile_index );
            SrcFilePoint( srcfile );
            TokenLine = 0;
            TokenColumn = 0;
            CurToken = getToken( r, &rt, &stop );
            if( CurToken == T_REWRITE_MODS ) {
                code_byte = getByte( r, &rt, &stop );
            }
        }
    }
    if( CurToken == T_REWRITE_MODS ) {
        for( ;; ) {
            if( code_byte == CODE_ABS ) {
                getBinary( r, &rt, &stop, (uint_8*)&absolute, sizeof( absolute ) );
                if( MASK_ABS_LINE & absolute ) {
                    TokenLine = absolute & ~MASK_ABS_LINE;
                    TokenColumn = 0;
                } else {
                    TokenColumn = absolute;
                    break;
                }
            } else if( MASK_DELTA_LINE & code_byte ) {
                TokenLine += code_byte & ~MASK_DELTA_LINE;
            } else {
                TokenColumn += code_byte;
                break;
            }
            code_byte = getByte( r, &rt, &stop );
        }
        CurToken = getToken( r, &rt, &stop );
    }
    switch( CurToken ) {
    case T_ID:
    case T_BAD_CHAR:
        len = getString( r, &rt, &stop, Buffer );
        TokenLen = len;
        break;
    case T_BAD_TOKEN:
        getBinary( r, &rt, &stop, (uint_8*)&BadTokenInfo, sizeof( BadTokenInfo ) );
        break;
    case T_STRING:
    case T_LSTRING:
        len = getString( r, &rt, &stop, Buffer );
        TokenLen = len + 1;
        break;
    case T_CONSTANT:
        getBinary( r, &rt, &stop, (uint_8*)&ConstType, sizeof( ConstType ) );
        switch( ConstType ) {
        case TYP_LONG_DOUBLE:
        case TYP_DOUBLE:
        case TYP_FLOAT:
            len = getString( r, &rt, &stop, Buffer );
            TokenLen = len;
            break;
        default:
            getBinary( r, &rt, &stop, (uint_8*)&Constant64, sizeof( Constant64 ) );
            break;
        }
        break;
    default:
        break;
    }
#ifndef NDEBUG
    CtxScanToken();
    DumpToken();
#endif
}
Example #24
0
void FetchClientPrivate::packet_ready()
{
    if (m_socket->readBuffer.readPos() == m_socket->readBuffer.writePos())
        return;
    for (;;){
        if (m_state == Data){
            unsigned size = m_socket->readBuffer.writePos() - m_socket->readBuffer.readPos();
            if (size){
                if (!m_client->write_data(m_socket->readBuffer.data(m_socket->readBuffer.readPos()), size)){
                    m_socket->error_state("Write error");
                    return;
                }
            }
            m_received += size;
            if (m_received >= m_size){
                m_state = Done;
                m_socket->error_state("");
                return;
            }
            m_socket->readBuffer.init(0);
            m_socket->readBuffer.packetStart();
            return;
        }
        log_packet(m_socket->readBuffer, false, HTTPPacket);
        string line;
        string opt;
        if (!read_line(line)){
            m_socket->readBuffer.init(0);
            m_socket->readBuffer.packetStart();
            return;
        }
        switch (m_state){
        case None:
#ifdef USE_OPENSSL
        case SSLConnect:
#endif
            if (getToken(line, ' ').substr(0, 5) != "HTTP/"){
                m_socket->error_state("Bad HTTP answer");
                return;
            }
            m_code = atol(getToken(line, ' ').c_str());
            m_state = Header;
            break;
        case Header:
            if (line.empty()){
                m_state = Data;
                break;
            }
            m_hIn += line;
            m_hIn += '\x00';
            opt = getToken(line, ':');
            if (opt == "Content-Length"){
                const char *p;
                for (p = line.c_str(); *p; p++)
                    if (*p != ' ')
                        break;
                m_size = atol(p);
            }
            if ((opt == "Location") && m_bRedirect){
                const char *p;
                for (p = line.c_str(); *p; p++)
                    if (*p != ' ')
                        break;
                string proto;
                string host;
                string user;
                string pass;
                string uri;
                string extra;
                unsigned short port;
                if (!FetchClient::crackUrl(p, proto, host, port, user, pass, uri, extra)){
                    FetchClient::crackUrl(m_uri.c_str(), proto, host, port, user, pass, uri, extra);
                    extra = "";
                    if (*p == '/'){
                        uri = p;
                    }else{
                        int n = uri.find_last_of('/');
                        uri = uri.substr(0, n + 1);
                        uri += p;
                    }
                }
                m_uri = proto;
                m_uri += "://";
                m_uri += host;
                m_uri += ":";
                m_uri += number(port);
                m_uri += uri;
                if (!extra.empty()){
                    m_uri += "?";
                    m_uri += extra;
                }
                m_state = Redirect;
                m_socket->close();
                m_socket->error_state("");
                return;
            }
            break;
        default:
            break;
        }
    }
}
Example #25
0
int sqlite3GetToken(const unsigned char *z, int *tokenType){
  return getToken(z, tokenType);
}
Example #26
0
/*
  Returns the next token, if # was met.  This function interprets the
  preprocessor directive, skips over any #ifdef'd out tokens, and returns the
  token after all of that.
*/
int Tokenizer::getTokenAfterPreprocessor()
{
    yyCh = getChar();
    while (isspace(yyCh) && yyCh != '\n')
        yyCh = getChar();

    /*
      #directive condition
    */
    QString directive;
    QString condition;

    while (isalpha(yyCh)) {
        directive += QChar(yyCh);
        yyCh = getChar();
    }
    if (!directive.isEmpty()) {
        while (yyCh != EOF && yyCh != '\n') {
            if (yyCh == '\\') {
                yyCh = getChar();
                if (yyCh == '\r')
                    yyCh = getChar();
            }
            condition += yyCh;
            yyCh = getChar();
        }
        condition.remove(*comment);
        condition = condition.simplified();

        /*
          The #if, #ifdef, #ifndef, #elif, #else, and #endif
          directives have an effect on the skipping stack.  For
          instance, if the code processed so far is

              #if 1
              #if 0
              #if 1
              // ...
              #else

          the skipping stack contains, from bottom to top, false true
          true (assuming 0 is false and 1 is true).  If at least one
          entry of the stack is true, the tokens are skipped.

          This mechanism is simple yet hard to understand.
        */
        if (directive[0] == QChar('i')) {
            if (directive == QString("if"))
                pushSkipping(!isTrue(condition));
            else if (directive == QString("ifdef"))
                pushSkipping(!defines->exactMatch(condition));
            else if (directive == QString("ifndef"))
                pushSkipping(defines->exactMatch(condition));
        } else if (directive[0] == QChar('e')) {
            if (directive == QString("elif")) {
                bool old = popSkipping();
                if (old)
                    pushSkipping(!isTrue(condition));
                else
                    pushSkipping(true);
            } else if (directive == QString("else")) {
                pushSkipping(!popSkipping());
            } else if (directive == QString("endif")) {
                popSkipping();
            }
        } else if (directive == QString("define")) {
            if (versionX->exactMatch(condition))
                yyVersion = versionX->cap(1);
        }
    }

    int tok;
    do {
        /*
          We set yyLex now, and after getToken() this will be
          yyPrevLex. This way, we skip over the preprocessor
          directive.
        */
        qstrcpy(yyLex, yyPrevLex);

        /*
          If getToken() meets another #, it will call
          getTokenAfterPreprocessor() once again, which could in turn
          call getToken() again, etc. Unless there are 10,000 or so
          preprocessor directives in a row, this shouldn't overflow
          the stack.
        */
        tok = getToken();
    } while (yyNumPreprocessorSkipping > 0 && tok != Tok_Eoi);
    return tok;
}
Example #27
0
struct statementNode* stmt()
{
	struct statementNode* stm;
	struct printStatement* prt;
	struct varNode* temp;

	ttype = getToken();
	
	if (ttype == ID) // assign_stmt
	{	printf("stmt ID: %d\n",ttype);
		stm = make_stmt(ASSIGNSTMT);
		
		printf("token: %s\n",token);
		stm->assignSt = assignment(token);
		stm->stmtType = ASSIGNSTMT;

		ttype = getToken();
		if (ttype == SEMICOLON)
		{	printf("SEMICOLON: %d\n",ttype);
			return stm;
		}
		else
		{	
			return NULL;
		}
	} 
	else if (ttype == WHILE) // while_stmt
	{	
		ungetToken();
		stm = make_stmt(WHILESTMT);
		stm->whileSt = whileStatement();
		stm->stmtType = WHILESTMT;

		ttype = getToken();
		if(ttype = RBRACE)
		{
			return stm;
		}
		else
		{
			return NULL;
		}
	} 
	else if (ttype == IF)
	{
		ungetToken();
		stm = make_stmt(IFSTMT);
		stm->ifSt = ifSt();
		stm->stmtType = IFSTMT;

		ttype = getToken();
		if(ttype = RBRACE)
		{
			return stm;
		}
		else
		{
			return NULL;
		}
	}
	else if (ttype == PRINT)
	{
		printf("stmt PRINT: %d\n",ttype);
		stm = make_stmt(PRINTSTMT);

		ttype = getToken();
		printf("token: %s\n",token);
		temp = symSearch(token);
		stm->stmtType = PRINTSTMT;

		if(temp != NULL)
		{	
			prt = make_printSt(temp);
			stm->printSt = prt;
			
			ttype = getToken();
			if(ttype == SEMICOLON)
			{
				return stm;
			}
			else
			{
				return NULL;
			}
		}
		else
		{
			return NULL;
		}

		//return stm;
	}
	else 
	{
		return NULL;
	}	
}
Example #28
0
bool Download::operator==(const Download* d) const {
	return compare(getToken(), d->getToken()) == 0;
}
Example #29
0
struct conditionNode* condition()
{
	struct conditionNode* cNode;
	struct varNode* op1;
	struct varNode* op2;
	struct statementNode* tBranch;
	struct statementNode* fBranch;
	int op;

	cNode = make_condition();

	ttype = getToken();
	if ((ttype == ID)|(ttype == NUM))
	{
		ungetToken(); //ungetToken since it still be parsed
		cNode->op1 = primary(); //left operand of a condition is a primary

		ttype = getToken();
		if ((ttype == GREATER)|(ttype == GTEQ)|(ttype == LESS)
			|(ttype == NOTEQUAL)|(ttype == LTEQ))
		{
			cNode->operator = ttype; //relop is set to >, <, etc.
		
			ttype = getToken();
			if ((ttype == ID)|(ttype == NUM))
			{
				ungetToken(); //ungetToken since it still be parsed
				cNode->op2 = primary(); //right operand of a condition is a primary
			
				ttype = getToken();
				if(ttype == RPAREN)
				{
					ttype = getToken();
					if(ttype == THEN)
					{
						cNode->trueBranch = stmt_list();
						return cNode;
					}
					else
					{
						return NULL;
					}
				}
				else
				{
					return NULL;
				}
			}
			else
			{
				return NULL;
			}
		}
		else
		{
			return NULL;
		}
	}
	else
	{
		return NULL;
	}
}
Example #30
0
void CommandsDefPrivate::generateConfig()
{
    if (cfg.size())
        return;
    if (config.length()){
        list<unsigned> processed;
        string active = config;
        string noactive;
        int n = config.find('/');
        if (n >= 0){
            active   = config.substr(0, n);
            noactive = config.substr(n + 1);
        }
        while (active.length()){
            string v = getToken(active, ',');
            unsigned id = atol(v.c_str());
            cfg.push_back(id);
            if (id)
                processed.push_back(id);
        }
        while (noactive.length()){
            string v = getToken(noactive, ',');
            unsigned id = atol(v.c_str());
            if (id)
                processed.push_back(id);
        }
        for (list<CommandDef>::iterator it = buttons.begin(); it != buttons.end(); ++it){
            CommandDef &c = (*it);
            unsigned grp = m_bMenu ? c.menu_grp : c.bar_grp;
            if (grp == 0)
                continue;
            list<unsigned>::iterator it_p;
            for (it_p = processed.begin(); it_p != processed.end(); ++it_p)
                if ((*it_p) == c.id)
                    break;
            if (it_p != processed.end())
                continue;
            unsigned cur_grp = 0;
            for (it_p = cfg.begin(); it_p != cfg.end(); ++it_p){
                if ((*it_p) == 0){
                    if (cur_grp == grp)
                        break;
                    continue;
                }
                list<CommandDef>::iterator itl;
                for (itl = buttons.begin(); itl != buttons.end(); ++itl)
                    if ((*itl).id == (*it_p))
                        break;
                if (itl == buttons.end())
                    continue;
                unsigned itl_grp = m_bMenu ? (*itl).menu_grp : (*itl).bar_grp;
                if (itl_grp == 0)
                    continue;
                cur_grp = itl_grp;
                if (grp > cur_grp)
                    break;
            }
            cfg.insert(it_p, c.id);
        }
    }else{
        unsigned cur_grp = 0;
        for (list<CommandDef>::iterator it = buttons.begin(); it != buttons.end(); ++it){
            CommandDef &c = (*it);
            unsigned grp = m_bMenu ? c.menu_grp : c.bar_grp;
            if (grp == 0)
                continue;
            if ((grp & ~0xFF) != (cur_grp & ~0xFF)){
                if (cur_grp)
                    cfg.push_back(0);
            }
            cur_grp = grp;
            cfg.push_back(c.id);
        }
    }
}