Exemple #1
0
task main( ){

	setSensorMode(COLOR, 8);
	delay(1000);
	setSensorMode(COLOR, 2);

	init();

	isFinal();

	while( hasAnyCityLeft() ) {
		if( current_deep == max_deep ){
			isFinal();
			backToParent();
			continue;
		}
		turnToNextDirection();
		verifyOrigin();

		while( !goToSon() ){
			turnAntiClockWise();
			if( current_direction == parents_map[current_x][current_y] ){
				backToParent();
				continue;
			}

		}
	}

}
/** HandleData
 * Final letter analysis for logical-visual decision.
 * Look for evidence that the received buffer is either logical Hebrew or 
 * visual Hebrew.
 * The following cases are checked:
 * 1) A word longer than 1 letter, ending with a final letter. This is an 
 *    indication that the text is laid out "naturally" since the final letter 
 *    really appears at the end. +1 for logical score.
 * 2) A word longer than 1 letter, ending with a Non-Final letter. In normal
 *    Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi, should not end with
 *    the Non-Final form of that letter. Exceptions to this rule are mentioned
 *    above in isNonFinal(). This is an indication that the text is laid out
 *    backwards. +1 for visual score
 * 3) A word longer than 1 letter, starting with a final letter. Final letters 
 *    should not appear at the beginning of a word. This is an indication that 
 *    the text is laid out backwards. +1 for visual score.
 *
 * The visual score and logical score are accumulated throughout the text and 
 * are finally checked against each other in GetCharSetName().
 * No checking for final letters in the middle of words is done since that case
 * is not an indication for either Logical or Visual text.
 *
 * The input buffer should not contain any white spaces that are not (' ')
 * or any low-ascii punctuation marks. 
 */
nsProbingState nsHebrewProber::HandleData(const char* aBuf, PRUint32 aLen)
{
  // Both model probers say it's not them. No reason to continue.
  if (GetState() == eNotMe)
    return eNotMe;

  const char *curPtr, *endPtr = aBuf+aLen;
  char cur;

  for (curPtr = (char*)aBuf; curPtr < endPtr; ++curPtr)
  {
    cur = *curPtr;
    if (cur == ' ') // We stand on a space - a word just ended
    {
      if (mBeforePrev != ' ') // *(curPtr-2) was not a space so prev is not a 1 letter word
      {
        if (isFinal(mPrev)) // case (1) [-2:not space][-1:final letter][cur:space]
          ++mFinalCharLogicalScore;
        else if (isNonFinal(mPrev)) // case (2) [-2:not space][-1:Non-Final letter][cur:space]
          ++mFinalCharVisualScore;
      }
    }
    else  // Not standing on a space
    {
      if ((mBeforePrev == ' ') && (isFinal(mPrev)) && (cur != ' ')) // case (3) [-2:space][-1:final letter][cur:not space]
        ++mFinalCharVisualScore;
    }
    mBeforePrev = mPrev;
    mPrev = cur;
  }

  // Forever detecting, till the end or until both model probers return eNotMe (handled above).
  return eDetecting;
}
bool PushDownAutomaton::compute(string tape, ofstream& ofs)
{
#ifdef DEBUG
	ofs << "BFS Simulation using the tape: " << tape << endl << endl;
#endif // DEBUG

	if (tape.size() == 0)
	{
#ifdef DEBUG
		ofs << "fita em branco" << endl;
#endif // DEBUG

		return isFinal(initial_state_);
	}

	queue<SimulationState> simulation_queue;
	simulation_queue.push(SimulationState(initial_state_, stack<char>(), 0, *this));

	while (!simulation_queue.empty())
	{
		SimulationState current = simulation_queue.front();
		simulation_queue.pop();

#ifdef DEBUG
		ofs << "--pop: " << current.toString() << endl;
#endif // DEBUG

		char head = current.tape_position < static_cast<int>(tape.size()) ? tape[current.tape_position] : epsilon;
		vector<pair<Transition, SimulationState> > nextStates = current.next(head, ofs);
		for (auto next : nextStates)
		{
			Transition& t = next.first;
			SimulationState& ss = next.second;

#ifdef DEBUG
			ofs <<"\t>" << t.toString() << " => ";
			ofs << ss.toString() << endl;
#endif // DEBUG

			// check if computation has stopped
			if (ss.tape_position == tape.size() && isFinal(ss.state) && ss.memory.empty())
			{

#ifdef DEBUG
				ofs << "-----pop: " << ss.toString() << endl;
#endif // DEBUG
				return true;
			}
			simulation_queue.push(ss);
		}
	}
	return false;
}
void execute(Robot *r, int *b)
{
	Move *m = getMoves(r);
	int i;
	
  #pragma omp for private(i)
	for (i=0;i<4;++i)
  {
    Move move = *(m+i);
	  if (moveValid(move,b))
    {
	    if (isFinal(move))
	      myResult++;
	    else 
      {
	      Robot *newRobot = (Robot*)malloc(sizeof(Robot));
	      newRobot->x = move.x;
	      newRobot->y = move.y;
	      newRobot->steps = r->steps+1;
	      newRobot->r = r;
	      execute(newRobot,b);
	      free(newRobot);
	    }
	  }
	}
	free(m);
}
Exemple #5
0
void SceneRecycle::run()
{
    while(!isFinal())
    {
	zThread::msleep(3000);
	DWORD delNum = npcList.size()/5;
	if(delNum)
	{
	    std::set<SceneNpc *> npcDelList;
	    for(DWORD i=0; i<delNum; i++)
	    {
		npcDelList.insert(npcList.front());
		npcList.pop();
	    }
#ifdef _WC1_DEBUG
	    if(!npcDelList.empty())
		Zebra::logger->debug("[Recycle]delete %u npc", npcDelList.size());
#endif
	    for(std::set<SceneNpc *>::iterator di = npcDelList.begin(); di!=npcDelList.end(); di++)
	    {
		delete *di;
	    }
	    npcDelList.clear();
	}
    }
}
void Foam::singleRegionSolutionControl::updateFinal() const
{
    mesh_.data::remove("finalIteration");

    if (isFinal())
    {
        mesh_.data::add("finalIteration", true);
    }
}
void ZebraClientTimeTick::run()
{
	while(!isFinal())
	{
		zThread::msleep(50);
		ZebraClientManager::getInstance()->timeAction();

	}
}
Exemple #8
0
/**
 * \brief 线程主函数
 *
 */
void ClientTimeTick::run()
{
  while(!isFinal())
  {
    //获取当前时间
    currentTime.now();
    ClientManager::getInstance().timeAction();
    zThread::msleep(50);
  }
}
Exemple #9
0
void print_access(u2 flags) {
	if(isPublic(flags))
		printf("public ");
	if(isPrivate(flags))
		printf("private ");
	if(isProtected(flags))
		printf("protected ");
	if(isFinal(flags))
		printf("final ");
	if(isAbstract(flags))
		printf("abstract ");
	if(isStatic(flags))
		printf("static ");
}
Exemple #10
0
void FLTimeTick::run()
{
    Zebra::logger->debug("FLTimeTick::run()");
    while(!isFinal())
    {
	zThread::sleep(1);
	zTime ct;
	if (ct.sec() % 10 == 0)
	{
	    LoginTimeout cb(ct);
	    LoginManager::getInstance().execAll(cb);
	}
    }
}
Exemple #11
0
 void StreamRender::Update(){


     QTimer::singleShot(30, this, SLOT(render())); // el consumo de cpu es 0

    if (isFinal())
    {
        // if(Timer->isActive ())
        // {
            Timer->stop();
             emit  Finish();
        // }
     }


}
void RecycleThread::run()
{
	TcpTask_IT it;
	while(!isFinal())
	{
		this->setRuning();
		check_queue();
		if(!tasks.empty())
		{
			for(it = tasks.begin();it != tasks.end();)
			{
				TcpTask *task = *it;
				switch(task->recycleConn())
				{
					case 1:
						{
							it = tasks.erase(it);
							if(task->isUnique())
							{
								task->uniqueRemove();
							}
							task->getNextState();
							DELETE(task);
						}
						break;
					case 0:
						{
							it++;
						}
						break;
				}
			}
		}
		Thread::msleep(200);
	}
	for(it = tasks.begin();it != tasks.end();)
	{
		TcpTask *task = *it;
		it = tasks.erase(it);
		if(task->isUnique())
		{
			task->uniqueRemove();
		}
		task->getNextState();
		DELETE(task);
	}
}
/**
 * \brief 线程主函数
 *
 */
void GatewayTimeTick::run()
{
	while(!isFinal())
	{
		zThread::sleep(1);

		//获取当前时间
		currentTime.now();

		if (one_second(currentTime) ) {
			LoginSessionManager::getInstance().update(currentTime);

			GatewayTaskCheckTime gtct;
			GatewayTaskManager::getInstance().execAll(gtct);
		}
	}
}
Exemple #14
0
void SwissGroup::initGroupName()
{
  int cnt = _players.count();
  if ( isFinal() ) {
    _name = QObject::tr( "Final" ); 
  } else if ( isHalfFinal() ) {
    _name = QObject::tr( "1/2 Final" );
  } else if ( isQuarterFinal() ) {
    _name = QObject::tr( "1/4 Final" );
  } else {
    int begin = _fromPlace;
    int end = _fromPlace + cnt - 1;
		_name =  QString( "%1 - %2" )
		     					.arg( begin ) // humans start counting from 1
				      		.arg( end );
  }
}
Exemple #15
0
void State::print(const Automaton& automaton) const
{
    std::cout << "Nom(" << name << ") ";
    if (isInitial()) {
        std::cout << "[initial] ";
    }
    if (isFinal()) {
        std::cout << "[final] ";
    }
    std::cout << std::endl;

    std::cout << "\t== Transitions" << std::endl;

    TransitionSet::const_iterator it;
    for (it = outTransitions.begin(); it != outTransitions.end(); ++it) {
        std::cout << "\t\tavec(" << it->condition << ") => " << automaton.findStateName(it->target) << std::endl;
    }
}
Exemple #16
0
//------------------------------------------------------------------------------
std::string WebSocketFrame::toString() const
{
    std::stringstream ss;
    ss << "Flags:";
    ss << " CONT="    << (isContinuation() ? "Y" : "N");
    ss << ", TXT="    << (isText()         ? "Y" : "N");
    ss << ", BIN="    << (isBinary()       ? "Y" : "N");
    ss << ", CLOSE="  << (isClose()        ? "Y" : "N");
    ss << ", PING="   << (isPing()         ? "Y" : "N");
    ss << ", PONG="   << (isPong()         ? "Y" : "N");
    ss << ", FINAL="  << (isFinal()        ? "Y" : "N");
    ss << ", RSV1="   << (isRSV1()         ? "Y" : "N");
    ss << ", RSV2="   << (isRSV2()         ? "Y" : "N");
    ss << ", RSV3="   << (isRSV3()         ? "Y" : "N");
    ss << ", nBytes=" << size();
    ss << ", bytes="  << getText();
    
    return ss.str();
}
void InterpreterDraft6::exitInterpreter() {
#if VERBOSE
	std::cout << "Exiting interpreter " << _name << std::endl;
#endif
	NodeSet<std::string> statesToExit = _configuration;
	statesToExit.forward(false);
	statesToExit.sort();

	for (int i = 0; i < statesToExit.size(); i++) {
		Arabica::XPath::NodeSet<std::string> onExitElems = filterChildElements(_nsInfo.xmlNSPrefix + "onexit", statesToExit[i]);
		for (int j = 0; j < onExitElems.size(); j++) {
			executeContent(onExitElems[j]);
		}
		Arabica::XPath::NodeSet<std::string> invokeElems = filterChildElements(_nsInfo.xmlNSPrefix + "invoke", statesToExit[i]);
		// TODO: we ought to cancel all remaining invokers just to be sure with the persist extension
		for (int j = 0; j < invokeElems.size(); j++) {
			cancelInvoke(invokeElems[j]);
		}
		if (isFinal(statesToExit[i]) && parentIsScxmlState(statesToExit[i])) {
			returnDoneEvent(statesToExit[i]);
		}
	}
	_configuration = NodeSet<std::string>();
}
Exemple #18
0
void SuperTimeTick::run()
{
  readTime();

  while(!isFinal())
  {
    zThread::sleep(1);

    currentTime.now();
    Zebra::qwGameTime = qwStartGameTime + startTime.elapse(currentTime) / 1000;
    
    if (0 != Zebra::qwGameTime
        && 0 == Zebra::qwGameTime % 600)
    {
      saveTime();
    }

    Cmd::Super::t_GameTime tCmd;
    tCmd.qwGameTime = Zebra::qwGameTime;
    ServerManager::getInstance().broadcast(&tCmd,sizeof(tCmd));
  }

  saveTime();
}
Exemple #19
0
void SessionTimeTick::run()
{
	//int rush = 0;
	while(!isFinal())
	{
		zThread::msleep(50);

		//获取当前时间
		currentTime.now();

		recordClient->doCmd();
		SessionTaskManager::getInstance().execEvery();
		if (_five_sec(currentTime))
		{
		    HeroCardManager::getMe().timer();	//��������ƥ��
		}
#if 0
		if (_five_sec(currentTime)) {
			CDareM::getMe().timer();
			CNpcDareM::getMe().timer();
			CCityM::getMe().timer();
			CArmyM::getMe().timer();
		}

		if (_one_sec(currentTime))
		{
			CQuizM::getMe().timer();
			CUnionM::getMe().timer();
			CAllyM::getMe().timer();
			CArenaManager::getInstance().Arena_timer();
		}

		if (_ten_min(currentTime))
		{
			AuctionService::getMe().checkDB();
		}
#endif
		// [ranqd Add] Session每五分钟同步一次服务器在线状态
		if( _five_min(currentTime) )
		{
			UserSessionManager::getInstance()->notifyOnlineToGate();
		}

		if (_one_min(currentTime))
		{
			SessionService::getInstance().checkShutdown();
#if 0
			//SessionService::getInstance().checkGumu();
			CCountryM::getMe().timer();
			//CGemM::getMe().timer();
			CartoonPetService::getMe().writeAllToDB();
			EmperorForbid::getMe().timer();
#endif
			//定时动作
			time_t timValue = time(NULL);
			struct tm tmValue;
			zRTime::getLocalTime(tmValue,timValue);
			SessionService::getInstance().checkCountry(tmValue);

			//GM公告
			for (int i=0; i<=5; i++)
			{
				if (SessionService::wMsg[i].time)
				{
					if (SessionService::wMsg[i].count)
						SessionService::wMsg[i].count--;
					else
					{
						if (SessionService::wMsg[i].country)
							if (SessionService::wMsg[i].mapID)//区域公告
							{
								SceneSession *scene = SceneSessionManager::getInstance()
									->getSceneByID((SessionService::wMsg[i].country<<16)+SessionService::wMsg[i].mapID);
								if (scene)
								{
									Cmd::Session::t_broadcastScene_SceneSession send;
									strncpy(send.info,SessionService::wMsg[i].msg,MAX_CHATINFO);
									strncpy(send.GM,SessionService::wMsg[i].GM,MAX_NAMESIZE);
									send.mapID = (SessionService::wMsg[i].country<<16)+SessionService::wMsg[i].mapID;
									scene->sendCmd(&send,sizeof(send));
#ifdef _DEBUG
									Zebra::logger->debug("GM公告:%s:%s mapID=%u",send.GM,send.info,send.mapID);
#endif
								}
							}
							else//国家公告
								SessionChannel::sendCountryInfo(Cmd::INFO_TYPE_SCROLL,SessionService::wMsg[i].country,SessionService::wMsg[i].msg);
						else//世界公告
							SessionChannel::sendAllInfo(Cmd::INFO_TYPE_SCROLL,SessionService::wMsg[i].msg);

						SessionService::wMsg[i].count = SessionService::wMsg[i].interval;
						SessionService::wMsg[i].time--;
					}
				}
				if (0==SessionService::wMsg[i].time)
					SessionService::wMsg.erase(i);
			}
		}
#if 0
		if (_one_hour(currentTime))
		{
			MailService::getMe().checkDB();
			CVoteM::getMe().timer();
			CCountryM::getMe().timerPerHour();
			CCountryM::getMe().save();
		}
#endif
	}
}
Exemple #20
0
void GateTimeTick::run()
{
	DWORD step = 0;
	SDWORD maxFrameNum = 100;
	while(!isFinal())
	{
		setRuning();
		QWORD begin = 0,end = 0; 
		struct timespec tv_begin;
		clock_gettime(CLOCK_REALTIME,&tv_begin);
		begin = tv_begin.tv_sec*1000L + tv_begin.tv_nsec/1000000L;
		
		GatewayServer::getInstance().doCmd();
		GateTaskManager::getInstance().doCmd();
		recordClient->doCmd();
		sessionClient->doCmd();
		if(m_oneSec(s_currentTime)) 
		{
			oneSec();
			if(m_fiveSec(s_currentTime))
			{
				fiveSec();
			}
			else if(m_tenSec(GateTimeTick::s_currentTime))
			{
				tenSec();
			}
			else if(m_oneMin(s_currentTime))
			{
				oneMin();
			}
			else if(m_fiveMin(s_currentTime))
			{
				fiveMin();
			}
			else if(m_oneQuarter(s_currentTime))
			{
				oneQuarter();
			}
			else if(m_oneClocker(s_currentTime))
			{
				oneHour();
			}
			else if(m_zeroClocker(s_currentTime))
			{
				zeroHour();
			}
			else if(m_fourClocker(s_currentTime))
			{
				fourHour();
			}
		}
		++step;
		GatewayServer::getInstance().checkFinal();
		struct timespec tv_end;
		clock_gettime(CLOCK_REALTIME,&tv_end);
		end = tv_end.tv_sec*1000L + tv_end.tv_nsec/1000000L;

		m_frameTime = end - begin;

		if(maxFrameNum)
		{
			maxFrameNum -= 1;
			if(m_frameTime > m_maxFrameTime)
			{
				m_maxFrameTime = m_frameTime;
			}
		}
		else
		{
			maxFrameNum = 100;
			m_maxFrameTime = 0;
		}
		if(m_frameTime > 300)
		{
			Global::logger->debug("服务器运行桢数过慢 当前桢:%lu ms",m_frameTime);
		}
		if(m_frameTime < 10)
		{
			Thread::msleep(10 - m_frameTime);
		}
	}
	gateFinal();
}
Exemple #21
0
void VarDeclaration::semantic(Scope *sc)
{
#if 0
    printf("VarDeclaration::semantic('%s', parent = '%s')\n", toChars(), sc->parent->toChars());
    printf(" type = %s\n", type ? type->toChars() : "null");
    printf(" stc = x%x\n", sc->stc);
    printf(" storage_class = x%x\n", storage_class);
    printf("linkage = %d\n", sc->linkage);
    //if (strcmp(toChars(), "mul") == 0) halt();
#endif

    storage_class |= sc->stc;
    if (storage_class & STCextern && init)
        error("extern symbols cannot have initializers");

    AggregateDeclaration *ad = isThis();
    if (ad)
        storage_class |= ad->storage_class & STC_TYPECTOR;

    /* If auto type inference, do the inference
     */
    int inferred = 0;
    if (!type)
    {   inuse++;
        type = init->inferType(sc);
        inuse--;
        inferred = 1;

        /* This is a kludge to support the existing syntax for RAII
         * declarations.
         */
        storage_class &= ~STCauto;
        originalType = type;
    }
    else
    {   if (!originalType)
            originalType = type;
        type = type->semantic(loc, sc);
    }
    //printf(" semantic type = %s\n", type ? type->toChars() : "null");

    type->checkDeprecated(loc, sc);
    linkage = sc->linkage;
    this->parent = sc->parent;
    //printf("this = %p, parent = %p, '%s'\n", this, parent, parent->toChars());
    protection = sc->protection;
    //printf("sc->stc = %x\n", sc->stc);
    //printf("storage_class = x%x\n", storage_class);

#if DMDV2
    if (storage_class & STCgshared && global.params.safe && !sc->module->safe)
    {
        error("__gshared not allowed in safe mode; use shared");
    }
#endif

    Dsymbol *parent = toParent();
    FuncDeclaration *fd = parent->isFuncDeclaration();

    Type *tb = type->toBasetype();
    if (tb->ty == Tvoid && !(storage_class & STClazy))
    {   error("voids have no value");
        type = Type::terror;
        tb = type;
    }
    if (tb->ty == Tfunction)
    {   error("cannot be declared to be a function");
        type = Type::terror;
        tb = type;
    }
    if (tb->ty == Tstruct)
    {   TypeStruct *ts = (TypeStruct *)tb;

        if (!ts->sym->members)
        {
            error("no definition of struct %s", ts->toChars());
        }
    }
    if ((storage_class & STCauto) && !inferred)
       error("storage class 'auto' has no effect if type is not inferred, did you mean 'scope'?");

    if (tb->ty == Ttuple)
    {   /* Instead, declare variables for each of the tuple elements
         * and add those.
         */
        TypeTuple *tt = (TypeTuple *)tb;
        size_t nelems = Parameter::dim(tt->arguments);
        Objects *exps = new Objects();
        exps->setDim(nelems);
        Expression *ie = init ? init->toExpression() : NULL;

        for (size_t i = 0; i < nelems; i++)
        {   Parameter *arg = Parameter::getNth(tt->arguments, i);

            OutBuffer buf;
            buf.printf("_%s_field_%zu", ident->toChars(), i);
            buf.writeByte(0);
            const char *name = (const char *)buf.extractData();
            Identifier *id = Lexer::idPool(name);

            Expression *einit = ie;
            if (ie && ie->op == TOKtuple)
            {   einit = (Expression *)((TupleExp *)ie)->exps->data[i];
            }
            Initializer *ti = init;
            if (einit)
            {   ti = new ExpInitializer(einit->loc, einit);
            }

            VarDeclaration *v = new VarDeclaration(loc, arg->type, id, ti);
            //printf("declaring field %s of type %s\n", v->toChars(), v->type->toChars());
            v->semantic(sc);

#if !IN_LLVM
// removed for LDC since TupleDeclaration::toObj already creates the fields;
// adding them to the scope again leads to duplicates
            if (sc->scopesym)
            {   //printf("adding %s to %s\n", v->toChars(), sc->scopesym->toChars());
                if (sc->scopesym->members)
                    sc->scopesym->members->push(v);
            }
#endif

            Expression *e = new DsymbolExp(loc, v);
            exps->data[i] = e;
        }
        TupleDeclaration *v2 = new TupleDeclaration(loc, ident, exps);
        v2->isexp = 1;
        aliassym = v2;
        return;
    }

    if (storage_class & STCconst && !init && !fd)
        // Initialize by constructor only
        storage_class = (storage_class & ~STCconst) | STCctorinit;

    if (isConst())
    {
    }
    else if (isStatic())
    {
    }
    else if (isSynchronized())
    {
        error("variable %s cannot be synchronized", toChars());
    }
    else if (isOverride())
    {
        error("override cannot be applied to variable");
    }
    else if (isAbstract())
    {
        error("abstract cannot be applied to variable");
    }
    else if (storage_class & STCtemplateparameter)
    {
    }
    else if (storage_class & STCctfe)
    {
    }
    else
    {
        AggregateDeclaration *aad = sc->anonAgg;
        if (!aad)
            aad = parent->isAggregateDeclaration();
        if (aad)
        {
#if DMDV2
            assert(!(storage_class & (STCextern | STCstatic | STCtls | STCgshared)));

            if (storage_class & (STCconst | STCimmutable) && init)
            {
                if (!type->toBasetype()->isTypeBasic())
                    storage_class |= STCstatic;
            }
            else
#endif
                aad->addField(sc, this);
        }

        InterfaceDeclaration *id = parent->isInterfaceDeclaration();
        if (id)
        {
            error("field not allowed in interface");
        }

        /* Templates cannot add fields to aggregates
         */
        TemplateInstance *ti = parent->isTemplateInstance();
        if (ti)
        {
            // Take care of nested templates
            while (1)
            {
                TemplateInstance *ti2 = ti->tempdecl->parent->isTemplateInstance();
                if (!ti2)
                    break;
                ti = ti2;
            }

            // If it's a member template
            AggregateDeclaration *ad = ti->tempdecl->isMember();
            if (ad && storage_class != STCundefined)
            {
                error("cannot use template to add field to aggregate '%s'", ad->toChars());
            }
        }
    }

#if DMDV2
    if ((storage_class & (STCref | STCparameter | STCforeach)) == STCref &&
        ident != Id::This)
    {
        error("only parameters or foreach declarations can be ref");
    }
#endif

    if (type->isscope() && !noscope)
    {
        if (storage_class & (STCfield | STCout | STCref | STCstatic) || !fd)
        {
            error("globals, statics, fields, ref and out parameters cannot be auto");
        }

        if (!(storage_class & STCscope))
        {
            if (!(storage_class & STCparameter) && ident != Id::withSym)
                error("reference to scope class must be scope");
        }
    }

    enum TOK op = TOKconstruct;
    if (!init && !sc->inunion && !isStatic() && !isConst() && fd &&
        !(storage_class & (STCfield | STCin | STCforeach)) &&
        type->size() != 0)
    {
        // Provide a default initializer
        //printf("Providing default initializer for '%s'\n", toChars());
        if (type->ty == Tstruct &&
            ((TypeStruct *)type)->sym->zeroInit == 1)
        {   /* If a struct is all zeros, as a special case
             * set it's initializer to the integer 0.
             * In AssignExp::toElem(), we check for this and issue
             * a memset() to initialize the struct.
             * Must do same check in interpreter.
             */
            Expression *e = new IntegerExp(loc, 0, Type::tint32);
            Expression *e1;
            e1 = new VarExp(loc, this);
            e = new AssignExp(loc, e1, e);
            e->op = TOKconstruct;
            e->type = e1->type;         // don't type check this, it would fail
            init = new ExpInitializer(loc, e);
            return;
        }
        else if (type->ty == Ttypedef)
        {   TypeTypedef *td = (TypeTypedef *)type;
            if (td->sym->init)
            {   init = td->sym->init;
                ExpInitializer *ie = init->isExpInitializer();
                if (ie)
                    // Make copy so we can modify it
                    init = new ExpInitializer(ie->loc, ie->exp);
            }
            else
                init = getExpInitializer();
        }
        else
        {
            init = getExpInitializer();
        }
        // Default initializer is always a blit
        op = TOKblit;
    }

    if (init)
    {
        sc = sc->push();
        sc->stc &= ~(STC_TYPECTOR | STCpure | STCnothrow | STCref);

        ArrayInitializer *ai = init->isArrayInitializer();
        if (ai && tb->ty == Taarray)
        {
            init = ai->toAssocArrayInitializer();
        }

        StructInitializer *si = init->isStructInitializer();
        ExpInitializer *ei = init->isExpInitializer();

        // See if initializer is a NewExp that can be allocated on the stack
        if (ei && isScope() && ei->exp->op == TOKnew)
        {   NewExp *ne = (NewExp *)ei->exp;
            if (!(ne->newargs && ne->newargs->dim))
            {   ne->onstack = 1;
                onstack = 1;
                if (type->isBaseOf(ne->newtype->semantic(loc, sc), NULL))
                    onstack = 2;
            }
        }

        // If inside function, there is no semantic3() call
        if (sc->func)
        {
            // If local variable, use AssignExp to handle all the various
            // possibilities.
            if (fd && !isStatic() && !isConst() && !init->isVoidInitializer())
            {
                //printf("fd = '%s', var = '%s'\n", fd->toChars(), toChars());
                if (!ei)
                {
                    Expression *e = init->toExpression();
                    if (!e)
                    {
                        init = init->semantic(sc, type);
                        e = init->toExpression();
                        if (!e)
                        {   error("is not a static and cannot have static initializer");
                            return;
                        }
                    }
                    ei = new ExpInitializer(init->loc, e);
                    init = ei;
                }

                Expression *e1 = new VarExp(loc, this);

                Type *t = type->toBasetype();
                if (t->ty == Tsarray && !(storage_class & (STCref | STCout)))
                {
                    ei->exp = ei->exp->semantic(sc);
                    if (!ei->exp->implicitConvTo(type))
                    {
                        int dim = ((TypeSArray *)t)->dim->toInteger();
                        // If multidimensional static array, treat as one large array
                        while (1)
                        {
                            t = t->nextOf()->toBasetype();
                            if (t->ty != Tsarray)
                                break;
                            dim *= ((TypeSArray *)t)->dim->toInteger();
                            e1->type = new TypeSArray(t->nextOf(), new IntegerExp(0, dim, Type::tindex));
                        }
                    }
                    e1 = new SliceExp(loc, e1, NULL, NULL);
                }
                else if (t->ty == Tstruct)
                {
                    ei->exp = ei->exp->semantic(sc);
                    ei->exp = resolveProperties(sc, ei->exp);
                    StructDeclaration *sd = ((TypeStruct *)t)->sym;
#if DMDV2
                    /* Look to see if initializer is a call to the constructor
                     */
                    if (sd->ctor &&             // there are constructors
                        ei->exp->type->ty == Tstruct && // rvalue is the same struct
                        ((TypeStruct *)ei->exp->type)->sym == sd &&
                        ei->exp->op == TOKstar)
                    {
                        /* Look for form of constructor call which is:
                         *    *__ctmp.ctor(arguments...)
                         */
                        PtrExp *pe = (PtrExp *)ei->exp;
                        if (pe->e1->op == TOKcall)
                        {   CallExp *ce = (CallExp *)pe->e1;
                            if (ce->e1->op == TOKdotvar)
                            {   DotVarExp *dve = (DotVarExp *)ce->e1;
                                if (dve->var->isCtorDeclaration())
                                {   /* It's a constructor call, currently constructing
                                     * a temporary __ctmp.
                                     */
                                    /* Before calling the constructor, initialize
                                     * variable with a bit copy of the default
                                     * initializer
                                     */
                                    Expression *e = new AssignExp(loc, new VarExp(loc, this), t->defaultInit(loc));
                                    e->op = TOKblit;
                                    e->type = t;
                                    ei->exp = new CommaExp(loc, e, ei->exp);

                                    /* Replace __ctmp being constructed with e1
                                     */
                                    dve->e1 = e1;
                                    return;
                                }
                            }
                        }
                    }
#endif
                    if (!ei->exp->implicitConvTo(type))
                    {
                        /* Look for opCall
                         * See bugzilla 2702 for more discussion
                         */
                        Type *ti = ei->exp->type->toBasetype();
                        // Don't cast away invariant or mutability in initializer
                        if (search_function(sd, Id::call) &&
                            /* Initializing with the same type is done differently
                             */
                            !(ti->ty == Tstruct && t->toDsymbol(sc) == ti->toDsymbol(sc)))
                        {   // Rewrite as e1.call(arguments)
                            Expression * eCall = new DotIdExp(loc, e1, Id::call);
                            ei->exp = new CallExp(loc, eCall, ei->exp);
                        }
                    }
                }
                ei->exp = new AssignExp(loc, e1, ei->exp);
                ei->exp->op = TOKconstruct;
                canassign++;
                ei->exp = ei->exp->semantic(sc);
                canassign--;
                ei->exp->optimize(WANTvalue);
            }
            else
            {
                init = init->semantic(sc, type);
                if (fd && isConst() && !isStatic())
                {   // Make it static
                    storage_class |= STCstatic;
                }
            }
        }
        else if (isConst() || isFinal() ||
                 parent->isAggregateDeclaration())
        {
            /* Because we may need the results of a const declaration in a
             * subsequent type, such as an array dimension, before semantic2()
             * gets ordinarily run, try to run semantic2() now.
             * Ignore failure.
             */

            if (!global.errors && !inferred)
            {
                unsigned errors = global.errors;
                global.gag++;
                //printf("+gag\n");
                Expression *e;
                Initializer *i2 = init;
                inuse++;
                if (ei)
                {
                    e = ei->exp->syntaxCopy();
                    e = e->semantic(sc);
                    e = e->implicitCastTo(sc, type);
                }
                else if (si || ai)
                {   i2 = init->syntaxCopy();
                    i2 = i2->semantic(sc, type);
                }
                inuse--;
                global.gag--;
                //printf("-gag\n");
                if (errors != global.errors)    // if errors happened
                {
                    if (global.gag == 0)
                        global.errors = errors; // act as if nothing happened
#if DMDV2
                    /* Save scope for later use, to try again
                     */
                    scope = new Scope(*sc);
                    scope->setNoFree();
#endif
                }
                else if (ei)
                {
                    if (isDataseg() || (storage_class & STCmanifest))
                        e = e->optimize(WANTvalue | WANTinterpret);
                    else
                        e = e->optimize(WANTvalue);
                    switch (e->op)
                    {
                        case TOKint64:
                        case TOKfloat64:
                        case TOKstring:
                        case TOKarrayliteral:
                        case TOKassocarrayliteral:
                        case TOKstructliteral:
                        case TOKnull:
                            ei->exp = e;            // no errors, keep result
                            break;

                        default:
#if DMDV2
                            /* Save scope for later use, to try again
                             */
                            scope = new Scope(*sc);
                            scope->setNoFree();
#endif
                            break;
                    }
                }
                else
                    init = i2;          // no errors, keep result
            }
        }
        sc = sc->pop();
    }
}
void InterpreterDraft6::enterStates(const Arabica::XPath::NodeSet<std::string>& enabledTransitions) {
	NodeSet<std::string> statesToEnter;
	NodeSet<std::string> statesForDefaultEntry;
	monIter_t monIter;

#if VERBOSE
	std::cout << _name << ": Enabled enter transitions: " << std::endl;
	for (int i = 0; i < enabledTransitions.size(); i++) {
		std::cout << "\t" << enabledTransitions[i] << std::endl;
	}
	std::cout << std::endl;
#endif

	for (int i = 0; i < enabledTransitions.size(); i++) {
		Element<std::string> transition = ((Element<std::string>)enabledTransitions[i]);
		if (!isTargetless(transition)) {
			std::string transitionType = (iequals(transition.getAttribute("type"), "internal") ? "internal" : "external");
			NodeSet<std::string> tStates = getTargetStates(transition);

#if VERBOSE
			std::cout << _name << ": Target States: ";
			for (int i = 0; i < tStates.size(); i++) {
				std::cout << ATTR(tStates[i], "id") << ", ";
			}
			std::cout << std::endl;
#endif

			Node<std::string> ancestor;
			Node<std::string> source = getSourceState(transition);
#if VERBOSE
			std::cout << _name << ": Source States: " << ATTR(source, "id") << std::endl;
#endif
			assert(source);

			bool allDescendants = true;
			for (int j = 0; j < tStates.size(); j++) {
				if (!isDescendant(tStates[j], source)) {
					allDescendants = false;
					break;
				}
			}
			if (iequals(transitionType, "internal") &&
			        isCompound(source) &&
			        allDescendants) {
				ancestor = source;
			} else {
				NodeSet<std::string> tmpStates;
				tmpStates.push_back(source);
				tmpStates.insert(tmpStates.end(), tStates.begin(), tStates.end());

				ancestor = findLCCA(tmpStates);
			}

#if VERBOSE
			std::cout << _name << ": Ancestor: " << ATTR(ancestor, "id") << std::endl;
#endif

			for (int j = 0; j < tStates.size(); j++) {
				addStatesToEnter(tStates[j], statesToEnter, statesForDefaultEntry);
			}

#if VERBOSE
			std::cout << _name << ": States to enter: ";
			for (int i = 0; i < statesToEnter.size(); i++) {
				std::cout << LOCALNAME(statesToEnter[i]) << ":" << ATTR(statesToEnter[i], "id") << ", ";
			}
			std::cout << std::endl;
#endif

			for (int j = 0; j < tStates.size(); j++) {
				NodeSet<std::string> ancestors = getProperAncestors(tStates[j], ancestor);

#if VERBOSE
				std::cout << _name << ": Proper Ancestors of " << ATTR(tStates[j], "id") << " and " << ATTR(ancestor, "id") << ": ";
				for (int i = 0; i < ancestors.size(); i++) {
					std::cout << ATTR(ancestors[i], "id") << ", ";
				}
				std::cout << std::endl;
#endif

				for (int k = 0; k < ancestors.size(); k++) {
					statesToEnter.push_back(ancestors[k]);
					if(isParallel(ancestors[k])) {
						NodeSet<std::string> childs = getChildStates(ancestors[k]);
						for (int l = 0; l < childs.size(); l++) {
							bool someIsDescendant = false;
							for (int m = 0; m < statesToEnter.size(); m++) {
								if (isDescendant(statesToEnter[m], childs[l])) {
									someIsDescendant = true;
									break;
								}
							}
							if (!someIsDescendant) {
								addStatesToEnter(childs[l], statesToEnter, statesForDefaultEntry);
							}
						}
					}
				}
			}
		}
	}
	statesToEnter.to_document_order();

#if VERBOSE
	std::cout << _name << ": States to enter: ";
	for (int i = 0; i < statesToEnter.size(); i++) {
		std::cout << ATTR(statesToEnter[i], "id") << ", ";
	}
	std::cout << std::endl;
#endif

	for (int i = 0; i < statesToEnter.size(); i++) {
		Element<std::string> stateElem = (Element<std::string>)statesToEnter[i];

		// extension for flattened interpreters
		for (unsigned int k = 0; k < statesToEnter.size(); k++) {
			NodeSet<std::string> invokes = filterChildElements(_nsInfo.xmlNSPrefix + "invoke", statesToEnter[k]);
			for (unsigned int j = 0; j < invokes.size(); j++) {
				if (HAS_ATTR(invokes[j], "persist") && DOMUtils::attributeIsTrue(ATTR(invokes[j], "persist"))) {
					invoke(invokes[j]);
				}
			}
		}

		// --- MONITOR: beforeEnteringState ------------------------------
		for(monIter_t monIter = _monitors.begin(); monIter != _monitors.end(); monIter++) {
			try {
				(*monIter)->beforeEnteringState(shared_from_this(), stateElem, (i + 1 < statesToEnter.size()));
			}
			USCXML_MONITOR_CATCH_BLOCK(beforeEnteringState)
		}

		// extension for flattened SCXML documents, we will need an explicit uninvoke element
		NodeSet<std::string> uninvokes = filterChildElements(_nsInfo.xmlNSPrefix + "uninvoke", statesToEnter[i]);
		for (int j = 0; j < uninvokes.size(); j++) {
			Element<std::string> uninvokeElem = (Element<std::string>)uninvokes[j];
			cancelInvoke(uninvokeElem);
		}

		_configuration.push_back(stateElem);
		_statesToInvoke.push_back(stateElem);

//		if (_binding == LATE && stateElem.getAttribute("isFirstEntry").size() > 0) {
		if (_binding == LATE && !isMember(stateElem, _alreadyEntered)) {
			NodeSet<std::string> dataModelElems = filterChildElements(_nsInfo.xmlNSPrefix + "datamodel", stateElem);
			if(dataModelElems.size() > 0 && _dataModel) {
				Arabica::XPath::NodeSet<std::string> dataElems = filterChildElements(_nsInfo.xmlNSPrefix + "data", dataModelElems[0]);
				for (int j = 0; j < dataElems.size(); j++) {
					if (dataElems[j].getNodeType() == Node_base::ELEMENT_NODE)
						initializeData(Element<std::string>(dataElems[j]));
				}
			}
			_alreadyEntered.push_back(stateElem);
//			stateElem.setAttribute("isFirstEntry", "");
		}
		// execute onentry executable content
		NodeSet<std::string> onEntryElems = filterChildElements(_nsInfo.xmlNSPrefix + "onEntry", stateElem);
		executeContent(onEntryElems, false);

		// --- MONITOR: afterEnteringState ------------------------------
		for(monIter_t monIter = _monitors.begin(); monIter != _monitors.end(); monIter++) {
			try {
				(*monIter)->afterEnteringState(shared_from_this(), stateElem, (i + 1 < statesToEnter.size()));
			}
			USCXML_MONITOR_CATCH_BLOCK(afterEnteringState)
		}

		if (isMember(stateElem, statesForDefaultEntry)) {
			// execute initial transition content for compound states
			Arabica::XPath::NodeSet<std::string> transitions = _xpath.evaluate("" + _nsInfo.xpathPrefix + "initial/" + _nsInfo.xpathPrefix + "transition", stateElem).asNodeSet();
			for (int j = 0; j < transitions.size(); j++) {
				executeContent(transitions[j]);
			}
		}

		if (isFinal(stateElem)) {
			internalDoneSend(stateElem);
			Element<std::string> parent = (Element<std::string>)stateElem.getParentNode();

			if (isParallel(parent.getParentNode())) {
				Element<std::string> grandParent = (Element<std::string>)parent.getParentNode();

				Arabica::XPath::NodeSet<std::string> childs = getChildStates(grandParent);
				bool inFinalState = true;
				for (int j = 0; j < childs.size(); j++) {
					if (!isInFinalState(childs[j])) {
						inFinalState = false;
						break;
					}
				}
				if (inFinalState) {
					internalDoneSend(parent);
				}
			}
		}
	}
	for (int i = 0; i < _configuration.size(); i++) {
		Element<std::string> stateElem = (Element<std::string>)_configuration[i];
		if (isFinal(stateElem) && parentIsScxmlState(stateElem)) {
			_running = false;
			_done = true;
		}
	}
}
void CheckConnectThread::run()
{
	while(!isFinal())
	{
		this->setRuning();
		Thread::sleep(1);
		Time ct;
		check_queue();
		for(TcpClientTaskBase_IT it = m_taskContainer.begin();it != m_taskContainer.end();)
		{
			TcpClientTaskBase *task = *it;
			switch(task->getState())
			{
			#if 0
				case TcpClientTaskBase::close:
					{
					#if 0
						if( !task->checkStateTimeout( TcpClientTaskBase::close,ct,4 ) )
						{
							if( task->connect() )
							{
								m_pool->addCheckWait( task );
							}
							else if( !task->needReConn() )
							{
								TcpClientTaskBase_IT temp = it;
								++it;
								m_taskContainer.erase( temp );
								task->resetState();
								SAFE_DELETE( task );
								continue;
							}
						}
					}
					#endif
					break;
				case TcpClientTaskBase::sync:
					break;
				case TcpClientTaskBase::okay:
					task->checkConn();
					break;
				case TcpClientTaskBase::recycle:
					#if 0
					if( task->checkStateTimeout( TcpClientTaskBase::recycle,ct,4 ) )
					{
						task->getNextState();
						if( !task->needReConn() )
						{
							TcpClientTaskBase_IT temp = it;
							++it;
							m_taskContainer.erase( temp );
							SAFE_DELETE( task );
							continue;
						}
					}
				#endif
				break;
			#endif
			}
			++it;
		}
	}
}
Exemple #24
0
/**
 * \brief 时间循环,发送定时事件,处理受影响npc ai等
 */
void SceneTimeTick::run()
{
  const int timeout_value = 500;
  const int timeout_value2 = 300;
  DWORD step = 0;
  int t = 0;
  while(!isFinal())
  {
    zThread::msleep((10-t)>0?(10-t):1);
    //获取当前时间
    currentTime.now();

	//sky 一秒记时器循环遍历队伍处理Roll事宜
	if(_one_sec(currentTime)) {
		SceneManager::getInstance().TeamRollItme();
	}

    if (_five_sec(currentTime)) {
      OnTimer event(1);
      EventTable::instance().execute(event);
      ScenesService::getInstance().checkAndReloadConfig();
    }
    sessionClient->doCmd();
    recordClient->doCmd();
    SceneTaskManager::getInstance().execEvery();

    //specialNpc
    //MonkeyNpcs affectNpc;
    //AddSpecialNpcCallBack asncb(affectNpc,step,t > timeout_value2);
    //SceneNpcManager::getMe().execAllSpecialNpc(asncb);
    SceneNpc::AI(currentTime,SceneNpcManager::getMe().getSepcialNpc(),step,t > timeout_value2);

    //250 usec
    EverySceneEntryAction esea(step);
    //对所有地图调用回调函数
    SceneManager::getInstance().execEveryScene(esea);

#if 0
    if (0==step)
    {
      //20-25 usec
      sessionClient->doCmd();
      recordClient->doCmd();
      SceneTaskManager::getInstance().execEvery();
    }
#endif

    if (_one_min(currentTime))
    {//竞赛处理,一分钟判断一次全国竞赛
      CountryDareM::getMe().timer();

      //刷新所有全局变量
      if (GlobalVar::server_id()) { //ugly,TO BE FIXED

        ALLVARS(update);
        ALLVARS(save);
      }

      SceneManager::getInstance().checkUnloadOneScene();
    }

    step = (++step) % MAX_NPC_GROUP;

    zRTime e;
    t = currentTime.elapse(e);
    if (t > timeout_value)
    {
      Xlogger->debug("---------- 1次循环用时 %u 毫秒----------",t);
    }

	scriptTaskManagement::getInstance().execAll();

	duplicateManager::getInstance().doClear();
	/*scriptTaskManagement::iterator it = _tasklist->begin();
	scriptTaskManagement::iterator end = _tasklist->end();
	for( ; it != end; ++it)
	{
		time_t t = (time(NULL) - it->second->lastTime);
		if(it->second->doTask(t))
		{
			it->second->lastTime = time(NULL);
		}
	}*/

  }
}
Exemple #25
0
void SessionTimeTick::run()
{
    DWORD step = 0;
    SDWORD maxFrameNum = 100;
    while(!isFinal())
    {
        setRuning();
        s_currentTime.now();
        struct timespec tv_begin;
        clock_gettime( CLOCK_REALTIME,&tv_begin );
        QWORD begin = tv_begin.tv_sec*1000L + tv_begin.tv_nsec/1000000L;

        recordClient->doCmd();
        SessionServer::getInstance().doCmd();
        SessionTaskManager::getInstance().doCmd();

        if(m_oneSec(s_currentTime))
        {
            oneSec();
            if(m_fiveSec(s_currentTime))
            {
                fiveSec();
            }
            else if(m_tenSec(s_currentTime))
            {
                tenSec();
            }
            else if(m_oneMin(s_currentTime))
            {
                oneMin();
            }
            else if(m_fiveMin(s_currentTime))
            {
                fiveMin();
            }
            else if(m_oneQuarter(s_currentTime))
            {
                oneQuarter();
            }
            else if(m_oneClocker(s_currentTime))
            {
                oneHour();
            }
            else if(m_zeroClocker(s_currentTime))
            {
                zeroHour();
            }
            else if(m_fourClocker(s_currentTime))
            {
                fourHour();
            }
        }
        ++step;
        struct timespec tv_end;
        clock_gettime(CLOCK_REALTIME,&tv_end);
        QWORD end = tv_end.tv_sec*1000L + tv_end.tv_nsec /1000000L;
        m_frameTime = end - begin;
        if(maxFrameNum)
        {
            maxFrameNum -= 1;
            if(m_frameTime > m_maxFrameTime)
            {
                m_maxFrameTime = m_frameTime;
            }
        }
        else
        {
            maxFrameNum = 100;
            m_maxFrameTime = 0;
        }
        LogInfoCheckConditionOnly(m_frameTime <= 300,"会话服务器运行桢数过慢%lums",m_frameTime );
        if(m_frameTime < 10)
        {
            Thread::msleep(10 - m_frameTime);
        }
    }
    sessionFinal();
}
Exemple #26
0
int FuncDeclaration::canInline(int hasthis, int hdrscan)
{
    InlineCostState ics;
    int cost;

#define CANINLINE_LOG 0

#if CANINLINE_LOG
    printf("FuncDeclaration::canInline(hasthis = %d, '%s')\n", hasthis, toChars());
#endif

    if (needThis() && !hasthis)
        return 0;

    if (inlineNest || (semanticRun < PASSsemantic3 && !hdrscan))
    {
#if CANINLINE_LOG
        printf("\t1: no, inlineNest = %d, semanticRun = %d\n", inlineNest, semanticRun);
#endif
        return 0;
    }

    switch (inlineStatus)
    {
    case ILSyes:
#if CANINLINE_LOG
        printf("\t1: yes %s\n", toChars());
#endif
        return 1;

    case ILSno:
#if CANINLINE_LOG
        printf("\t1: no %s\n", toChars());
#endif
        return 0;

    case ILSuninitialized:
        break;

    default:
        assert(0);
    }

    if (type)
    {   assert(type->ty == Tfunction);
        TypeFunction *tf = (TypeFunction *)(type);
#if IN_LLVM
        // LDC: Only extern(C) varargs count.
        if (tf->linkage != LINKd)
#endif
            if (tf->varargs == 1)   // no variadic parameter lists
                goto Lno;

        /* Don't inline a function that returns non-void, but has
         * no return expression.
         */
        if (tf->next && tf->next->ty != Tvoid &&
                !(hasReturnExp & 1) &&
                !hdrscan)
            goto Lno;
    }
#if !IN_LLVM
    // LDC: Only extern(C) varargs count, and ctors use extern(D).
    else
    {   CtorDeclaration *ctor = isCtorDeclaration();

        if (ctor && ctor->varargs == 1)
            goto Lno;
    }
#endif

    if (
        !fbody ||
        !hdrscan &&
        (
#if 0
            isCtorDeclaration() ||  // cannot because need to convert:
            //      return;
            // to:
            //      return this;
#endif
            isSynchronized() ||
            isImportedSymbol() ||
#if !IN_LLVM
#if DMDV2
            closureVars.dim ||      // no nested references to this frame
#else
            nestedFrameRef ||       // no nested references to this frame
#endif
#endif // !IN_LLVM
            (isVirtual() && !isFinal())
        ))
    {
        goto Lno;
    }

#if !IN_LLVM
#if !SARRAYVALUE
    /* If any parameters are Tsarray's (which are passed by reference)
     * or out parameters (also passed by reference), don't do inlining.
     */
    if (parameters)
    {
        for (size_t i = 0; i < parameters->dim; i++)
        {
            VarDeclaration *v = (VarDeclaration *)parameters->data[i];
            if (/*v->isOut() || v->isRef() ||*/ v->type->toBasetype()->ty == Tsarray)
                goto Lno;
        }
    }
#endif
#endif

    memset(&ics, 0, sizeof(ics));
    ics.hasthis = hasthis;
    ics.fd = this;
    ics.hdrscan = hdrscan;
    cost = fbody->inlineCost(&ics);
#if CANINLINE_LOG
    printf("cost = %d\n", cost);
#endif
    if (cost >= COST_MAX)
        goto Lno;

#if !IN_LLVM
    if (!hdrscan)    // Don't scan recursively for header content scan
        inlineScan();
#endif

    if (!hdrscan)    // Don't modify inlineStatus for header content scan
        inlineStatus = ILSyes;
#if CANINLINE_LOG
    printf("\t2: yes %s\n", toChars());
#endif
    return 1;

Lno:
    if (!hdrscan)    // Don't modify inlineStatus for header content scan
        inlineStatus = ILSno;
#if CANINLINE_LOG
    printf("\t2: no %s\n", toChars());
#endif
    return 0;
}
Exemple #27
0
int FuncDeclaration::canInline(int hasthis, int hdrscan, int statementsToo)
{
    InlineCostState ics;
    int cost;

#define CANINLINE_LOG 0

#if CANINLINE_LOG
    printf("FuncDeclaration::canInline(hasthis = %d, statementsToo = %d, '%s')\n", hasthis, statementsToo, toChars());
#endif

    if (needThis() && !hasthis)
        return 0;

    if (inlineNest || (semanticRun < PASSsemantic3 && !hdrscan))
    {
#if CANINLINE_LOG
        printf("\t1: no, inlineNest = %d, semanticRun = %d\n", inlineNest, semanticRun);
#endif
        return 0;
    }

#if 1
    switch (statementsToo ? inlineStatusStmt : inlineStatusExp)
    {
        case ILSyes:
#if CANINLINE_LOG
            printf("\t1: yes %s\n", toChars());
#endif
            return 1;

        case ILSno:
#if CANINLINE_LOG
            printf("\t1: no %s\n", toChars());
#endif
            return 0;

        case ILSuninitialized:
            break;

        default:
            assert(0);
    }
#endif

    if (type)
    {   assert(type->ty == Tfunction);
        TypeFunction *tf = (TypeFunction *)(type);
        if (tf->varargs == 1)   // no variadic parameter lists
            goto Lno;

        /* Don't inline a function that returns non-void, but has
         * no return expression.
         * No statement inlining for non-voids.
         */
        if (tf->next && tf->next->ty != Tvoid &&
            (!(hasReturnExp & 1) || statementsToo) &&
            !hdrscan)
            goto Lno;
    }

    if (
        !fbody ||
        ident == Id::ensure ||  // ensure() has magic properties the inliner loses
        !hdrscan &&
        (
#if 0
        isCtorDeclaration() ||  // cannot because need to convert:
                                //      return;
                                // to:
                                //      return this;
#endif
        isSynchronized() ||
        isImportedSymbol() ||
        hasNestedFrameRefs() ||      // no nested references to this frame
        (isVirtual() && !isFinal())
       ))
    {
        goto Lno;
    }

#if 0
    /* If any parameters are Tsarray's (which are passed by reference)
     * or out parameters (also passed by reference), don't do inlining.
     */
    if (parameters)
    {
        for (size_t i = 0; i < parameters->dim; i++)
        {
            VarDeclaration *v = parameters->tdata()[i];
            if (v->type->toBasetype()->ty == Tsarray)
                goto Lno;
        }
    }
#endif

    memset(&ics, 0, sizeof(ics));
    ics.hasthis = hasthis;
    ics.fd = this;
    ics.hdrscan = hdrscan;
    cost = fbody->inlineCost(&ics);
#if CANINLINE_LOG
    printf("cost = %d for %s\n", cost, toChars());
#endif
    if (tooCostly(cost))
        goto Lno;
    if (!statementsToo && cost > COST_MAX)
        goto Lno;

    if (!hdrscan)
    {
        // Don't modify inlineStatus for header content scan
        if (statementsToo)
            inlineStatusStmt = ILSyes;
        else
            inlineStatusExp = ILSyes;

        inlineScan();    // Don't scan recursively for header content scan

        if (inlineStatusExp == ILSuninitialized)
        {
            // Need to redo cost computation, as some statements or expressions have been inlined
            memset(&ics, 0, sizeof(ics));
            ics.hasthis = hasthis;
            ics.fd = this;
            ics.hdrscan = hdrscan;
            cost = fbody->inlineCost(&ics);
        #if CANINLINE_LOG
            printf("recomputed cost = %d for %s\n", cost, toChars());
        #endif
            if (tooCostly(cost))
                goto Lno;
            if (!statementsToo && cost > COST_MAX)
                goto Lno;

            if (statementsToo)
                inlineStatusStmt = ILSyes;
            else
                inlineStatusExp = ILSyes;
        }
    }
#if CANINLINE_LOG
    printf("\t2: yes %s\n", toChars());
#endif
    return 1;

Lno:
    if (!hdrscan)    // Don't modify inlineStatus for header content scan
    {   if (statementsToo)
            inlineStatusStmt = ILSno;
        else
            inlineStatusExp = ILSno;
    }
#if CANINLINE_LOG
    printf("\t2: no %s\n", toChars());
#endif
    return 0;
}
Exemple #28
0
bool Monster::findPath( Pos sour )
{
	this->parent = Pos(sour.x + 1, sour.y);
	Pos** record;
	record = new Pos *[mMapHeight];
	for(int i = 0; i < mMapHeight; ++i)
	{
		record[i] = new Pos[mMapWidth];
	}
	stack<CellNode> st = stack<CellNode>();
	CellNode node;
	node.self = sour;
	st.push(node);

	//判断从起点到终点之间是否有通路
	CellNode temp;
	while(true)
	{
		if(!st.empty())
		{
			temp = st.top();
			st.pop();
		}
		else
		{
			return false;
		}
		if(isFinal(temp.self))
		{
			if(isValid(temp.self))
			{
				markIt(temp.self);
				record[temp.self.y][temp.self.x] = temp.pare;
				parent = temp.pare;
			}
			break;
		}
		else
		{
			if(isValid(temp.self))
			{
				markIt(temp.self);
				record[temp.self.y][temp.self.x] = temp.pare;
				parent = temp.pare;
				pushPos(temp.self, st);
			}
		}
	}

	//// 如果有通路则寻找合适的路径
	Pos parent = finalPos;
	bool success = false;
	while(isValid(parent) && !success)
	{
		stepTo(parent);
		path.push_back(getStep());
		markIt(parent);
		parent = record[parent.y][parent.x];
		if(parent.x==sour.x && parent.y==sour.y)
		{
			success = true;
		}
	}
	path.push_back(fromPos);
	std::reverse(path.begin(),path.end());
	return true;
}
Exemple #29
0
string JPClass::describe()
{
	stringstream out;
	JPCleaner cleaner;
	out << "public ";
	if (isAbstract())
	{
		out << "abstract ";
	}
	if (isFinal())
	{
		out << "final ";
	}

	out << "class " << m_Name.getSimpleName();
	if (m_SuperClass != NULL)
	{
		out << " extends " << m_SuperClass->getName().getSimpleName();
	}

	if (m_SuperInterfaces.size() > 0)
	{
		out << " implements";
		bool first = true;
		for (vector<JPClass*>::iterator itf = m_SuperInterfaces.begin(); itf != m_SuperInterfaces.end(); itf++)
		{
			if (!first)
			{
				out << ",";
			}
			else
			{
				first = false;
			}
			JPClass* pc = *itf;
			out << " " << pc->getName().getSimpleName();
		}
	}
	out << endl << "{" << endl;

	// Fields
	out << "  // Accessible Static Fields" << endl;
	for (map<string, JPField*>::iterator curField = m_StaticFields.begin(); curField != m_StaticFields.end(); curField++)
	{
		JPField* f = curField->second;
		out << "  public static ";
		if (f->isFinal())
		{
			out << "final ";
		}
		out << f->getType().getSimpleName() << " " << f->getName() << ";" << endl;
	}
	out << endl;
	out << "  // Accessible Instance Fields" << endl;
	for (map<string, JPField*>::iterator curInstField = m_InstanceFields.begin(); curInstField != m_InstanceFields.end(); curInstField++)
	{
		JPField* f = curInstField->second;
		out << "  public ";
		if (f->isFinal())
		{
			out << "final ";
		}
		out << f->getType().getSimpleName() << " " << f->getName() << ";" << endl;
	}
	out << endl;

	// Constructors
	out << "  // Accessible Constructors" << endl;
	out << m_Constructors->describe("  ") << endl;

	out << "  // Accessible Methods" << endl;
	for (map<string, JPMethod*>::iterator curMethod = m_Methods.begin(); curMethod != m_Methods.end(); curMethod++)
	{
		JPMethod* f = curMethod->second;
		out << f->describe("  ");
		out << endl;
	}
	out << "}";

	return out.str();
}
Exemple #30
0
/**
 * \brief 时间循环,发送定时事件,处理受影响npc ai等
 */
void SceneTimeTick::run()
{
    const int timeout_value = 500;
    //  const int timeout_value2 = 300;
    DWORD step = 0;
    int t = 0;
    while(!isFinal())
    {
	zThread::msleep((10-t)>0?(10-t):1);
	//获取当前时间
	currentTime.now();
#if 0
	//sky 一秒记时器循环遍历队伍处理Roll事宜
	if(_one_sec(currentTime)) {
	    SceneManager::getInstance().TeamRollItme();
	}
#endif

#if 0
	if (_five_sec(currentTime)) {
	    OnTimer event(1);
	    EventTable::instance().execute(event);
	    ScenesService::getInstance().checkAndReloadConfig();
	}
#endif
	if(_one_sec(currentTime)) {
	    ChallengeGameManager::getMe().timer();
	}
	sessionClient->doCmd();
	recordClient->doCmd();
	SceneTaskManager::getInstance().execEvery();
#ifndef _MOBILE
	SceneNpc::AI(currentTime, SceneNpcManager::getMe().getSepcialNpc(), step, false);
#endif

	//250 usec
	EverySceneEntryAction esea(step);
	//对所有地图调用回调函数
	SceneManager::getInstance().execEveryScene(esea);
#if 0
	if (0==step)
	{
	    //20-25 usec
	    sessionClient->doCmd();
	    recordClient->doCmd();
	    SceneTaskManager::getInstance().execEvery();
	}
#endif

	if (_one_min(currentTime))
	{
#if 0 	//竞赛处理,一分钟判断一次全国竞赛
	    CountryDareM::getMe().timer();

	    if (Zebra::global["world_quiz"] == "true")
	    {
		struct tm tv1;
		time_t timValue = time(NULL);
		zRTime::getLocalTime(tv1,timValue);

		if (tv1.tm_hour==19)
		{
		    if (tv1.tm_min==5 || tv1.tm_min == 10 || tv1.tm_min==15)
		    {
			for (SceneManager::CountryMap_iter iter=SceneManager::getInstance().
				country_info.begin(); iter!=SceneManager::getInstance().country_info.end(); 
				iter++)
			{       
			    Cmd::Session::t_countryNotify_SceneSession send;
			    bzero(send.info,sizeof(send.info));
			    sprintf(send.info,"%d 分钟后举办智力竞赛",abs(20-tv1.tm_min));
			    send.dwCountryID = iter->second.id;
			    sessionClient->sendCmd(&send,sizeof(send));  
			}
		    }

		    if (!quiz && tv1.tm_min>=20 && tv1.tm_min<25)
		    {
			quiz = true;
			Cmd::Session::t_createQuiz_SceneSession send;

			send.active_time  = 30;
			send.ready_time   = 1;
			send.type = 0; 
			send.subject_type = 0;
			sessionClient->sendCmd(&send,sizeof(send));  
		    }
		}

		if (tv1.tm_hour==12)
		{
		    if (tv1.tm_min==5 || tv1.tm_min==10 || tv1.tm_min == 15)
		    {
			for (SceneManager::CountryMap_iter iter=SceneManager::getInstance().
				country_info.begin(); iter!=SceneManager::getInstance().country_info.end(); 
				iter++)
			{       
			    Cmd::Session::t_countryNotify_SceneSession send;
			    bzero(send.info,sizeof(send.info));
			    sprintf(send.info,"%d 分钟后举办智力竞赛",abs(20-tv1.tm_min));
			    send.dwCountryID = iter->second.id;
			    sessionClient->sendCmd(&send,sizeof(send));  
			}
		    }

		    if (!quiz && tv1.tm_min>=20 && tv1.tm_min<25)
		    {
			quiz = true;
			Cmd::Session::t_createQuiz_SceneSession send;

			send.active_time  = 30;
			send.ready_time   = 1;
			send.type = 0; 
			send.subject_type = 0;
			sessionClient->sendCmd(&send,sizeof(send));  
		    }
		}



		if (tv1.tm_hour==22)
		{
		    if (tv1.tm_min==35 || tv1.tm_min==40 || tv1.tm_min == 45)
		    {
			for (SceneManager::CountryMap_iter iter=SceneManager::getInstance().
				country_info.begin(); iter!=SceneManager::getInstance().country_info.end(); 
				iter++)
			{       
			    Cmd::Session::t_countryNotify_SceneSession send;
			    bzero(send.info,sizeof(send.info));
			    sprintf(send.info,"%d 分钟后举办智力竞赛",abs(50-tv1.tm_min));
			    send.dwCountryID = iter->second.id;
			    sessionClient->sendCmd(&send,sizeof(send));  
			}
		    }

		    if (!quiz && tv1.tm_min>=50 && tv1.tm_min<55)
		    {
			quiz = true;
			Cmd::Session::t_createQuiz_SceneSession send;

			send.active_time  = 30;
			send.ready_time   = 1;
			send.type = 0; 
			send.subject_type = 0;
			sessionClient->sendCmd(&send,sizeof(send));  
		    }
		}


		if (tv1.tm_hour==13 || tv1.tm_hour==20 || tv1.tm_hour==0)
		{
		    quiz = false;
		}
	    }
#endif
	    //刷新所有全局变量
	    if (GlobalVar::server_id()) { //ugly,TO BE FIXED

		ALLVARS(update);
		ALLVARS(save);
	    }
	    SceneManager::getInstance().checkUnloadOneScene();
	}

	++step;
	step %= MAX_NPC_GROUP;

	zRTime e;
	t = currentTime.elapse(e);
	if (t > timeout_value)
	{
	    Zebra::logger->debug("---------- 1次循环用时 %u 毫秒----------",t);
	}

	//scriptTaskManagement::getInstance().execAll();

	//duplicateManager::getInstance().doClear();
	/*scriptTaskManagement::iterator it = _tasklist->begin();
	  scriptTaskManagement::iterator end = _tasklist->end();
	  for( ; it != end; ++it)
	  {
	  time_t t = (time(NULL) - it->second->lastTime);
	  if(it->second->doTask(t))
	  {
	  it->second->lastTime = time(NULL);
	  }
	  }*/
    }
}