int main() {
	initgraph(640,480);
	
	char s[101];
	inputbox_getline("Input Box", "Input a string", s, 100);
	outtextxy(10,10,s);
	int x = getInteger();
	xyprintf(10,30,"This is an integer: %d",x);
	double y = getDouble();
	xyprintf(10,50,"This is a double: %f",y);
	getString(s, 100);
	outtextrect(10, 80, 100, 60, s);
	char c = getChar("Input a character");
	outtext(c);
	int  coords[4];
	int *pc = getCoords(coords, 2);
	line(pc[0], pc[1], pc[2], pc[3]);
	
	ege::getch();
	closegraph();  
	
	return 0;
}
示例#2
0
void
MIFrfile::skipImport()
{
  int ch;

  skipLine();

  while ((ch = getChar()) != EOF) {
    switch (ch) {
      case '&':
      case '=':
        skipLine();
        break;
      case '\n':
      case '\r':
      case ' ':
        break;
      default:
        ungetChar(ch);
        return;
    }
  }
}
示例#3
0
	char const* MTD_FLASHMEM ParameterReplacer::replaceTag(char const* curc)
	{
		char const* tagEnd;
		char const* tagStart = extractTagStr(curc, &tagEnd);
		if (getChar(tagStart) == '#')
		{
			// replace multiple parameters ('0param', '1param', ...)
			++tagStart;			
			uint32_t tagLen = tagEnd - tagStart;
			char tag[tagLen];
			f_memcpy(tag, tagStart, tagLen);
			tag[tagLen] = 0;
			for (uint32_t index = 0; ; ++index)
			{
				char const* fulltagname = f_printf(FSTR("%d%s"), index, tag);
				Params::Item* item = m_params->getItem(fulltagname);
				if (item)
					m_results.last()->addChunks(&item->value); // push parameter content
				else
					break;
			}
		}
		else
		{
			// replace one parameter
			Params::Item* item = m_params->getItem(tagStart, tagEnd);
			if (item)				
				m_results.last()->addChunks(&item->value); // push parameter content
            else if(m_blockParams)
            {
                BlockParams::Item* item = m_blockParams->getItem(tagStart, tagEnd);
                if (item)
                    m_results.last()->addChunks(item->value);   // push block parameter content
            }
		}
		return tagEnd + 2;	// bypass "}}"
	}
示例#4
0
int TdApi::reqInsertOrder(dict req)
{
	DFITCInsertOrderField myreq = DFITCInsertOrderField();
	memset(&myreq, 0, sizeof(myreq));
	getString(req, "instrumentID", myreq.instrumentID);
	getInt(req, "openCloseType", &myreq.openCloseType);
	getLong(req, "localOrderID", &myreq.localOrderID);
	getDouble(req, "insertPrice", &myreq.insertPrice);
	getChar(req, "orderProperty", myreq.orderProperty);
	getShort(req, "buySellType", &myreq.buySellType);
	getInt(req, "orderType", &myreq.orderType);
	getLong(req, "minMatchAmount", &myreq.minMatchAmount);
	getInt(req, "speculator", &myreq.speculator);
	getLong(req, "lRequestID", &myreq.lRequestID);
	getInt(req, "reservedType2", &myreq.reservedType2);
	getInt(req, "insertType", &myreq.insertType);
	getLong(req, "orderAmount", &myreq.orderAmount);
	getDouble(req, "profitLossPrice", &myreq.profitLossPrice);
	getString(req, "customCategory", myreq.customCategory);
	getInt(req, "instrumentType", &myreq.instrumentType);
	getString(req, "accountID", myreq.accountID);
	int i = this->api->ReqInsertOrder(&myreq);
	return i;
};
示例#5
0
char* readLine(void) {
	char* buffer;
	memfill(buffer, 100, 0);
	char c;
	word pos = 0;
	while (1) {
		c = getChar();
		if (c == '\b') {
			if (pos > 0) {
				buffer[--pos] = '\0';
				while (*buffer == ' ') buffer++;
				removeChar();
			}
		}	else
		if (c == '\n') {
			buffer[pos] = '\0';
			putChar('\n');
			return buffer;
		}	else {
			buffer[pos++] = c;
			putChar(c);
		}
	}
}
示例#6
0
//----------------------------------------------------------------------------------------------------------------------------------------------------------------
//FUNCION BAJA
int borrarPelicula(EMovie* movie, int length, int index)
{
 int i, auxReturn=-1, flag=-1;
 char activate;
 if(movie!=NULL && length>0)
 {
     for(i=0;i<length;i++)
     {
         if((movie+i)->isEmpty==0)
         {
             if((movie+i)->index==index)
             {
                 printf("el registro es:\nindice: %d, titulo: %s, genero: %s, puntaje: %d\n",(movie+i)->index,(movie+i)->titulo, (movie+i)->genero, (movie+i)->puntaje);
                 activate=getChar("Esta seguro que quiere modificar este registro?(s/n)\n");
                 if(activate=='s')
                 {
                     flag=0;
                     break;
                 }
             }
         }
         else
         {
             printf("El registro no existe o ya fue eliminado.\n");
             break;
         }
     }
     if(flag!=-1)
     {
         (movie+i)->isEmpty=1;
         printf("el registro se elimino correctamente.\n");
     }
     auxReturn=0;
 }
 return auxReturn;
}
示例#7
0
void accumulateValue(float* valuePtr, SyntaxErrorType errCode)
{
	float value = *valuePtr;
	//--------------------------------------------
	// Make sure the first character is a digit...
	if(calcCharCode(curChar) != CHR_DIGIT)
	{
		syntaxError(errCode);
		curToken = TKN_ERROR;
		return;
	}
	do
	{
		*tokenp = curChar;
		tokenp++;
		if(++digitCount <= MAX_DIGIT_COUNT)
			value = 10 * value + (curChar - '0');
		else
			countError = true;
		getChar();
	}
	while(calcCharCode(curChar) == CHR_DIGIT);
	*valuePtr = value;
}
示例#8
0
int main (int argc, char *argv[])
{
    DDRB = 0xFF;

    cli();

    //Init usart
    InitUSART();

    //Enable Global Interrupts. Sets SREG Interrupt bit.
    sei();

    //Intitialize LCD. Set Blinking cursor.
    lcd_cursor();
    
    //_delay_ms(10000);

    
    while(1){
        holder = getChar();
        if (holder != '\0') char_write(holder);
    }
    return 0; //should never get here.
}
示例#9
0
/**
 * Scans an integer value from the keyboard to the pointer *p.
 * @param *p The pointer of the result value.
 */
void USscanInt(int *p)
{
	acTask->writing = 1;
	scanUse = true;
	bool invert = false;
	char c;
	int i = 0;
	while(1)
	{
		c = getChar();
		if (c == '\n') break;
		else if (c == '-' && i == 0) invert = true;
		else
		{
			c -= 48;
			*p *= 10;
			*p += c;
			i++;
		}
	}
	if (invert) *p *= -1;
	scanUse = false;
	acTask->writing = 0;
}
示例#10
0
文件: NCUI.cpp 项目: ronw23/prime-osx
int
shNCursesInterface::getSpecialChar (SpecialKey *sk)
{
    int key = getChar ();
    switch (key) {
    case 27: *sk = kEscape; break;
    case ' ': *sk = kSpace; break;
    case KEY_ENTER: case 10: case 13: *sk = kEnter; break;
    case KEY_BACKSPACE: *sk = kBackSpace; break;
    case KEY_IC: *sk = kInsert; break;
    case KEY_DC: *sk = kDelete; break;
    case KEY_HOME:  case KEY_A1: *sk = kHome; break;
    case KEY_END:   case KEY_C1: *sk = kEnd; break;
    case KEY_PPAGE: case KEY_A3: *sk = kPgUp; break;
    case KEY_NPAGE: case KEY_C3: *sk = kPgDn; break;
    case KEY_UP: *sk = kUpArrow; break;
    case KEY_DOWN: *sk = kDownArrow; break;
    case KEY_LEFT: *sk = kLeftArrow; break;
    case KEY_RIGHT: *sk = kRightArrow; break;
    case KEY_B2: *sk = kCenter; break;
    default: *sk = kNoSpecialKey; break;
    }
    return key;
}
示例#11
0
void Sender::onReadyRead() {
    // Check whether error occurs
    if (getChar(socket) != 0) {
        closeAll();
        emit error();
        return;
    }

    QByteArray buf;
    switch (step) {
    case SEND_SIZE:
        file = new QFile(filepath);
        if (!file->open(QFile::ReadOnly)) {
            closeAll();
            emit error();
            return;
        }
        socket->write(QByteArray::number(file->size()));
        socket->flush();
        step = SEND_DATA;
        break;

    case SEND_DATA:
        buf = file->read(4096);
        if (!buf.isEmpty()) {
            socket->write(buf);
            socket->flush();
        }
        else { // finish
            closeAll();
            emit finished();
        }
        break;
    default:break;
    }
}
示例#12
0
int main() {
  printf(
	 "============================================\n"	\
	 "<expr> -> <term> {(+|-)<term>}\n"			\
	 "<term> -> <factor> {(*|/)<factor>}\n"			\
	 "<expr> -> id | int_constant | ( <expr>)\n"		\
	 "============================================\n\n"
	 );

  in_fp = fopen("expression.in", "r");

  if (in_fp == NULL) {
    printf("ERROR: Cannot open `expression.in` file");
  } else {
    getChar();

    do {
      lex();
      expr();
    } while (nextToken != EOF);
  }

  return 0;
}
示例#13
0
	void Drum:: Show(int a)
	{
		{/*
		dcoord.X = a;
		dcoord.Y = 12;
		SetConsoleCursorPosition( dhConsole, dcoord );*/
		ConsoleWorker::SetConsolePosition(a,12);

		cout<<pCur->symbol<<endl;
				/*
	dcoord.X = a;
		dcoord.Y = 13;
		SetConsoleCursorPosition( dhConsole, dcoord );*/
		ConsoleWorker::SetConsolePosition(a,13);

		cout<<getChar()<<' ';
		/*dcoord.X = a;
		dcoord.Y = 14;
		SetConsoleCursorPosition( dhConsole, dcoord );*/
		ConsoleWorker::SetConsolePosition(a,14);

		cout<<pHead->symbol<<endl;
		}
	}
示例#14
0
void cMenu::ThinkTextBox(int index)
{

	char* curChar = getChar();

	std::string dicka = curChar;

	dicka.erase(1);
	char* newcurChar = strdup(curChar);

	curChar = newcurChar;

	if( strstr(curChar, ".") )
	{

		if(TextBoxes[index].cursor > 0)
		{
			TextBoxes[index].Variable->erase( TextBoxes[index].cursor - 1, TextBoxes[index].cursor );

			TextBoxes[index].cursor = TextBoxes[index].cursor - 1;

		}

		return;
	}

	if ( strstr(curChar, "-") )
		return;
	

	TextBoxes[index].Variable->append( curChar );

	TextBoxes[index].cursor = TextBoxes[index].cursor + 1;


}
示例#15
0
文件: OEditor.cpp 项目: zonbrisad/ore
void OEditor::UpdateCursor() {
  int i;
  int nls;  // newlines
  int l;
  
//   find the number of newlines
  nls = 0;
  for (i=bufpos; i<=CursorPos; i++) {
    //if (i>0) 
      if (getChar(i) == '\n') {
        nls++;
      }
  }
  cury = nls;
  
  l = buf.lastIndexOf('\n', CursorPos); // search backwards
  DebugInt(l);
  if (l==-1) {
    curx = CursorPos;     // we are on first row
  } else {
    //curx = CursorPos - buf.lastIndexOf('\n', CursorPos) ;
    curx = CursorPos - l;
  }
}
示例#16
0
文件: ex4.c 项目: franciscompinto/AC2
//void puts();
//void putc();
//void delay();
int main (void)
{
//configure uart
//ler buad
printStr("Insira o valor de baud");
int buad=readInt10();

//ler parity
printStr("paridade: ");
char parity=getChar();

//ler stopbits

printStr("Stop bits: ");
int stopbits=readInt10();

//configurar com os values pretedendidos

configure_UART(buad,parity,stopbits);

while(1)
return 0;

}//end main
示例#17
0
t3Precedence t3Expression::getToken(int n)
{
    const char symbol = getChar(n);
    switch (symbol) {
        case '(':
            return lparen;
        case ')':
            return rparen;
        case '+':
            return plus;
        case '-':
            return minus;
        case '/':
            return divide;
        case '*':
            return times;
        case '%':
            return mod;
        case ' ':
            return eos;
        default:
            return operand;
    }
}
示例#18
0
int TdApi::reqExecOrderInsert(dict req, int nRequestID)
{
	CThostFtdcInputExecOrderField myreq = CThostFtdcInputExecOrderField();
	memset(&myreq, 0, sizeof(myreq));
	getStr(req, "InstrumentID", myreq.InstrumentID);
	getStr(req, "ExecOrderRef", myreq.ExecOrderRef);
	getChar(req, "CloseFlag", &myreq.CloseFlag);
	getChar(req, "OffsetFlag", &myreq.OffsetFlag);
	getChar(req, "PosiDirection", &myreq.PosiDirection);
	getStr(req, "BusinessUnit", myreq.BusinessUnit);
	getChar(req, "HedgeFlag", &myreq.HedgeFlag);
	getStr(req, "UserID", myreq.UserID);
	getInt(req, "Volume", &myreq.Volume);
	getStr(req, "InvestorID", myreq.InvestorID);
	getStr(req, "BrokerID", myreq.BrokerID);
	getInt(req, "RequestID", &myreq.RequestID);
	getChar(req, "ActionType", &myreq.ActionType);
	getChar(req, "ReservePositionFlag", &myreq.ReservePositionFlag);
	int i = this->api->ReqExecOrderInsert(&myreq, nRequestID);
	return i;
};
示例#19
0
  int getToken()
  {
    // skip whitespace
    while (isspace(_lastChar) && _lastChar != '\r' && _lastChar != '\n')
    {
      _lastChar = getChar();
    }

    if (isalpha(_lastChar) || _lastChar == '_')
    {
      _identifier = _lastChar;
      while (isalnum(_lastChar = getChar()) || _lastChar == '-' || _lastChar == '_')
      {
        _identifier += _lastChar;
      }

      if (_identifier == "set")
        return TOK_SET;
      if (_identifier == "function")
        return TOK_FUNCTION;
      if (_identifier == "macro")
        return TOK_MACRO;
      if (_identifier == "endfunction")
        return TOK_ENDFUNCTION;
      if (_identifier == "endmacro")
        return TOK_ENDMACRO;
      return TOK_IDENTIFIER;
    }

    if (isdigit(_lastChar))
    {
      // very lax!! number detection
      _identifier = _lastChar;
      while (isalnum(_lastChar = getChar()) || _lastChar == '.' || _lastChar == ',')
      {
        _identifier += _lastChar;
      }
      return TOK_NUMBER_LITERAL;
    }

    if (_lastChar == '#')
    {
      _lastChar = getChar();
      if (_lastChar == '!')
      {
        // found a doxygen comment marker
        _identifier.clear();

        _lastChar = getChar();
        while (_lastChar != EOF && _lastChar != '\n' && _lastChar != '\r')
        {
          _identifier += _lastChar;
          _lastChar = getChar();
        }
        return TOK_DOXYGEN_COMMENT;
      }

      // skip the comment
      while (_lastChar != EOF && _lastChar != '\n' && _lastChar != '\r')
      {
        _lastChar = getChar();
      }
    }

    if (_lastChar == '"')
    {
      _lastChar = getChar();
      _identifier.clear();
      while (_lastChar != EOF && _lastChar != '"')
      {
        _identifier += _lastChar;
        _lastChar = getChar();
      }

      // eat the closing "
      _lastChar = getChar();
      return TOK_STRING_LITERAL;
    }

    // don't eat the EOF
    if (_lastChar == EOF)
      return TOK_EOF;

    // don't eat the EOL
    if (_lastChar == '\r' || _lastChar == '\n')
    {
      if (_lastChar == '\r')
        _lastChar = getChar();
      if (_lastChar == '\n')
        _lastChar = getChar();
      return TOK_EOL;
    }

    // return the character as its ascii value
    int thisChar = _lastChar;
    _lastChar = getChar();
    return thisChar;
  }
示例#20
0
void processSerialCommand()
{
  LCD_BACKLIGHT = 1;
  uartSendMsg("Check start\n");
  if (getChar() != 0xAA || getChar() != 0x55)
    return;
  uartSendMsg("Got start\n");
  unsigned char cmd = getChar();
  uartSendMsg("Got Command ");
  uartSendNum(cmd, 10);
  uartSendMsg("\n");

  switch(cmd)
  {
    case 'F':
      getFreqFromSerial(&radioSettings.rxFreqM, &radioSettings.rxFreqK);
      updateRDA1846Freq(radioSettings.rxFreqM, radioSettings.rxFreqK);
      break;
    case 'T':
      if(getChar() == '\r' && getChar() == '\n')
        rda1846TX();
      break;
    case 'R':
      if(getChar() == '\r' && getChar() == '\n')
        rda1846RX(1);
      break;
    case 'D':
      if(getChar() == '\r' && getChar() == '\n')
        rda1846TXDTMF(radioSettings.txDTMF, 6, 1000);
      break;
    case 'd':
      {
        uartSendMsg("Send Digital RTTY\n");

        unsigned char data = getChar()&0xFF;

        short time = getChar()&0xFF;
        time <<= 8;
        time |= getChar()&0xFF;

        if(getChar() == '\r' && getChar() == '\n')
          rda1846TXDigital(data, time,
              5796, //Mark 1.415Khz
              6492 //space 1.585Khz
              );
        uartSendMsg("Send Digital Done\n");
      }
      break;
    case 'S':
      {
        unsigned char addr = getChar()&0xFF;

        short data = getChar()&0xFF;
        data <<= 8;
        data |= getChar()&0xFF;

        if(getChar() == '\r' && getChar() == '\n')
        {
          uartSendMsg("Set: ");
          uartSendNum(addr, 16);
          uartSendMsg(" to ");
          uartSendNum(data, 16);
          uartSendMsg("\r\n");

          rda1846SetReg(addr, data); //, data);
        }
      }
      break;
  }
  LCD_BACKLIGHT = 0;

}
示例#21
0
文件: mt_lib.c 项目: ghl800/mt_on_sdl
int getChar_4lua(lua_State *L)
{
	putChar(L, getChar());
	
	return 1;
}
示例#22
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"));
}
示例#23
0
static int getToken()
{
    const char tab[] = "bfnrt\"\'\\";
    const char backTab[] = "\b\f\n\r\t\"\'\\";

    yyIdent.clear();
    yyComment.clear();
    yyString.clear();

    while ( yyCh != EOF ) {
        yyLineNo = yyCurLineNo;

        if ( yyCh.isLetter() || yyCh.toLatin1() == '_' ) {
            do {
                yyIdent.append(yyCh);
                yyCh = getChar();
            } while ( yyCh.isLetterOrNumber() || yyCh.toLatin1() == '_' );

            if (yyTok != Tok_Dot) {
                switch ( yyIdent.at(0).toLatin1() ) {
                case 'r':
                    if ( yyIdent == QLatin1String("return") )
                        return Tok_return;
                    break;
                case 'c':
                    if ( yyIdent == QLatin1String("class") )
                        return Tok_class;
                    break;
                case 'n':
                    if ( yyIdent == QLatin1String("null") )
                        return Tok_null;
                    break;
                }
            }
            switch ( yyIdent.at(0).toLatin1() ) {
            case 'T':
                // TR() for when all else fails
                if ( yyIdent == QLatin1String("TR") )
                    return Tok_tr;
                break;
            case 'p':
                if( yyIdent == QLatin1String("package") )
                    return Tok_Package;
                break;
            case 't':
                if ( yyIdent == QLatin1String("tr") )
                    return Tok_tr;
                if ( yyIdent == QLatin1String("translate") )
                    return Tok_translate;
            }
            return Tok_Ident;
        } else {
            switch ( yyCh.toLatin1() ) {

            case '/':
                yyCh = getChar();
                if ( yyCh == QLatin1Char('/') ) {
                    do {
                        yyCh = getChar();
                        if (yyCh == EOF)
                            break;
                        yyComment.append(yyCh);
                    } while (yyCh != QLatin1Char('\n'));
                    return Tok_Comment;

                } else if ( yyCh == QLatin1Char('*') ) {
                    bool metAster = false;
                    bool metAsterSlash = false;

                    while ( !metAsterSlash ) {
                        yyCh = getChar();
                        if ( yyCh == EOF ) {
                            yyMsg() << qPrintable(LU::tr("Unterminated Java comment.\n"));
                            return Tok_Comment;
                        }

                        yyComment.append( yyCh );

                        if ( yyCh == QLatin1Char('*') )
                            metAster = true;
                        else if ( metAster && yyCh == QLatin1Char('/') )
                            metAsterSlash = true;
                        else
                            metAster = false;
                    }
                    yyComment.chop(2);
                    yyCh = getChar();

                    return Tok_Comment;
                }
                break;
            case '"':
                yyCh = getChar();

                while ( yyCh != EOF && yyCh != QLatin1Char('\n') && yyCh != QLatin1Char('"') ) {
                    if ( yyCh == QLatin1Char('\\') ) {
                        yyCh = getChar();
                        if ( yyCh == QLatin1Char('u') ) {
                            yyCh = getChar();
                            uint unicode(0);
                            for (int i = 4; i > 0; --i) {
                                unicode = unicode << 4;
                                if( yyCh.isDigit() ) {
                                    unicode += yyCh.digitValue();
                                }
                                else {
                                    int sub(yyCh.toLower().toLatin1() - 87);
                                    if( sub > 15 || sub < 10) {
                                        yyMsg() << qPrintable(LU::tr("Invalid Unicode value.\n"));
                                        break;
                                    }
                                    unicode += sub;
                                }
                                yyCh = getChar();
                            }
                            yyString.append(QChar(unicode));
                        }
                        else if ( yyCh == QLatin1Char('\n') ) {
                            yyCh = getChar();
                        }
                        else {
                            yyString.append( QLatin1Char(backTab[strchr( tab, yyCh.toLatin1() ) - tab]) );
                            yyCh = getChar();
                        }
                    } else {
                        yyString.append(yyCh);
                        yyCh = getChar();
                    }
                }

                if ( yyCh != QLatin1Char('"') )
                    yyMsg() << qPrintable(LU::tr("Unterminated string.\n"));

                yyCh = getChar();

                return Tok_String;

            case ':':
                yyCh = getChar();
                return Tok_Colon;
            case '\'':
                yyCh = getChar();

                if ( yyCh == QLatin1Char('\\') )
                    yyCh = getChar();
                do {
                    yyCh = getChar();
                } while ( yyCh != EOF && yyCh != QLatin1Char('\'') );
                yyCh = getChar();
                break;
            case '{':
                yyCh = getChar();
                return Tok_LeftBrace;
            case '}':
                yyCh = getChar();
                return Tok_RightBrace;
            case '(':
                if (yyParenDepth == 0)
                    yyParenLineNo = yyCurLineNo;
                yyParenDepth++;
                yyCh = getChar();
                return Tok_LeftParen;
            case ')':
                if (yyParenDepth == 0)
                    yyParenLineNo = yyCurLineNo;
                yyParenDepth--;
                yyCh = getChar();
                return Tok_RightParen;
            case ',':
                yyCh = getChar();
                return Tok_Comma;
            case '.':
                yyCh = getChar();
                return Tok_Dot;
            case ';':
                yyCh = getChar();
                return Tok_Semicolon;
            case '+':
                yyCh = getChar();
                if (yyCh == QLatin1Char('+')) {
                    yyCh = getChar();
                    return Tok_PlusPlus;
                }
                if( yyCh == QLatin1Char('=') ) {
                    yyCh = getChar();
                    return Tok_PlusEq;
                }
                return Tok_Plus;
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            {
                QByteArray ba;
                ba += yyCh.toLatin1();
                yyCh = getChar();
                bool hex = yyCh == QLatin1Char('x');
                if ( hex ) {
                    ba += yyCh.toLatin1();
                    yyCh = getChar();
                }
                while ( hex ? isxdigit(yyCh.toLatin1()) : yyCh.isDigit() ) {
                    ba += yyCh.toLatin1();
                    yyCh = getChar();
                }
                bool ok;
                yyInteger = ba.toLongLong(&ok);
                if (ok) return Tok_Integer;
                break;
            }
            default:
                yyCh = getChar();
            }
        }
    }
    return Tok_Eof;
}
示例#24
0
int Tokenizer::getToken()
{
    char *t = yyPrevLex;
    yyPrevLex = yyLex;
    yyLex = t;

    while (yyCh != EOF) {
        yyTokLoc = yyCurLoc;
        yyLexLen = 0;

        if (isspace(yyCh)) {
            do {
                yyCh = getChar();
            } while (isspace(yyCh));
        }
        else if (isalpha(yyCh) || yyCh == '_') {
            do {
                yyCh = getChar();
            } while (isalnum(yyCh) || yyCh == '_');

            int k = hashKword(yyLex, yyLexLen);
            for (;;) {
                int i = kwordHashTable[k];
                if (i == 0) {
                    return Tok_Ident;
                }
                else if (i == -1) {
                    if (!parsingMacro && ignoredTokensAndDirectives->contains(yyLex)) {
                        if (ignoredTokensAndDirectives->value(yyLex)) { // it's a directive
                            int parenDepth = 0;
                            while (yyCh != EOF && (yyCh != ')' || parenDepth > 1)) {
                                if (yyCh == '(')
                                    ++parenDepth;
                                else if (yyCh == ')')
                                    --parenDepth;
                                yyCh = getChar();
                            }
                            if (yyCh == ')')
                                yyCh = getChar();
                        }
                        break;
                    }
                }
                else if (strcmp(yyLex, kwords[i - 1]) == 0) {
                    int ret = (int) Tok_FirstKeyword + i - 1;
                    if (ret != Tok_explicit && ret != Tok_inline && ret != Tok_typename)
                        return ret;
                    break;
                }

                if (++k == KwordHashTableSize)
                    k = 0;
            }
        }
        else if (isdigit(yyCh)) {
            do {
                yyCh = getChar();
            } while (isalnum(yyCh) || yyCh == '.' || yyCh == '+' ||
                      yyCh == '-');
            return Tok_Number;
        }
        else {
            switch (yyCh) {
            case '!':
            case '%':
                yyCh = getChar();
                if (yyCh == '=')
                    yyCh = getChar();
                return Tok_SomeOperator;
            case '"':
                yyCh = getChar();

                while (yyCh != EOF && yyCh != '"') {
                    if (yyCh == '\\')
                        yyCh = getChar();
                    yyCh = getChar();
                }
                yyCh = getChar();

                if (yyCh == EOF)
                    yyTokLoc.warning(tr("Unterminated C++ string literal"),
                                     tr("Maybe you forgot '/*!' at the beginning of the file?"));
                else
                    return Tok_String;
                break;
            case '#':
                return getTokenAfterPreprocessor();
            case '&':
                yyCh = getChar();
                if (yyCh == '&' || yyCh == '=') {
                    yyCh = getChar();
                    return Tok_SomeOperator;
                }
                else {
                    return Tok_Ampersand;
                }
            case '\'':
                yyCh = getChar();
                if (yyCh == '\\')
                    yyCh = getChar();
                do {
                    yyCh = getChar();
                } while (yyCh != EOF && yyCh != '\'');

                if (yyCh == EOF) {
                    yyTokLoc.warning(tr("Unterminated C++ character"
                                         " literal"));
                }
                else {
                    yyCh = getChar();
                    return Tok_Number;
                }
                break;
            case '(':
                yyCh = getChar();
                if (yyNumPreprocessorSkipping == 0)
                    yyParenDepth++;
                if (isspace(yyCh)) {
                    do {
                        yyCh = getChar();
                    } while (isspace(yyCh));
                    yyLexLen = 1;
                    yyLex[1] = '\0';
                }
                if (yyCh == '*') {
                    yyCh = getChar();
                    return Tok_LeftParenAster;
                }
                return Tok_LeftParen;
            case ')':
                yyCh = getChar();
                if (yyNumPreprocessorSkipping == 0)
                    yyParenDepth--;
                return Tok_RightParen;
            case '*':
                yyCh = getChar();
                if (yyCh == '=') {
                    yyCh = getChar();
                    return Tok_SomeOperator;
                } else {
                    return Tok_Aster;
                }
            case '^':
                yyCh = getChar();
                if (yyCh == '=') {
                    yyCh = getChar();
                    return Tok_SomeOperator;
                } else {
                    return Tok_Caret;
                }
            case '+':
                yyCh = getChar();
                if (yyCh == '+' || yyCh == '=')
                    yyCh = getChar();
                return Tok_SomeOperator;
            case ',':
                yyCh = getChar();
                return Tok_Comma;
            case '-':
                yyCh = getChar();
                if (yyCh == '-' || yyCh == '=') {
                    yyCh = getChar();
                } else if (yyCh == '>') {
                    yyCh = getChar();
                    if (yyCh == '*')
                        yyCh = getChar();
                }
                return Tok_SomeOperator;
            case '.':
                yyCh = getChar();
                if (yyCh == '*') {
                    yyCh = getChar();
                } else if (yyCh == '.') {
                    do {
                        yyCh = getChar();
                    } while (yyCh == '.');
                    return Tok_Ellipsis;
                } else if (isdigit(yyCh)) {
                    do {
                        yyCh = getChar();
                    } while (isalnum(yyCh) || yyCh == '.' || yyCh == '+' ||
                              yyCh == '-');
                    return Tok_Number;
                }
                return Tok_SomeOperator;
            case '/':
                yyCh = getChar();
                if (yyCh == '/') {
                    do {
                        yyCh = getChar();
                    } while (yyCh != EOF && yyCh != '\n');
                } else if (yyCh == '*') {
                    bool metDoc = false; // empty doc is no doc
                    bool metSlashAsterBang = false;
                    bool metAster = false;
                    bool metAsterSlash = false;

                    yyCh = getChar();
                    if (yyCh == '!')
                        metSlashAsterBang = true;

                    while (!metAsterSlash) {
                        if (yyCh == EOF) {
                            yyTokLoc.warning(tr("Unterminated C++ comment"));
                            break;
                        } else {
                            if (yyCh == '*') {
                                metAster = true;
                            } else if (metAster && yyCh == '/') {
                                metAsterSlash = true;
                            } else {
                                metAster = false;
                                if (isgraph(yyCh))
                                    metDoc = true;
                            }
                        }
                        yyCh = getChar();
                    }
                    if (metSlashAsterBang && metDoc)
                        return Tok_Doc;
                    else if (yyParenDepth > 0)
                        return Tok_Comment;
                } else {
                    if (yyCh == '=')
                        yyCh = getChar();
                    return Tok_SomeOperator;
                }
                break;
            case ':':
                yyCh = getChar();
                if (yyCh == ':') {
                    yyCh = getChar();
                    return Tok_Gulbrandsen;
                } else {
                    return Tok_Colon;
                }
            case ';':
                yyCh = getChar();
                return Tok_Semicolon;
            case '<':
                yyCh = getChar();
                if (yyCh == '<') {
                    yyCh = getChar();
                    if (yyCh == '=')
                        yyCh = getChar();
                    return Tok_SomeOperator;
                } else if (yyCh == '=') {
                    yyCh = getChar();
                    return Tok_SomeOperator;
                } else {
                    return Tok_LeftAngle;
                }
            case '=':
                yyCh = getChar();
                if (yyCh == '=') {
                    yyCh = getChar();
                    return Tok_SomeOperator;
                } else {
                    return Tok_Equal;
                }
            case '>':
                yyCh = getChar();
                if (yyCh == '>') {
                    yyCh = getChar();
                    if (yyCh == '=')
                        yyCh = getChar();
                    return Tok_SomeOperator;
                } else if (yyCh == '=') {
                    yyCh = getChar();
                    return Tok_SomeOperator;
                } else {
                    return Tok_RightAngle;
                }
            case '?':
                yyCh = getChar();
                return Tok_SomeOperator;
            case '[':
                yyCh = getChar();
                if (yyNumPreprocessorSkipping == 0)
                    yyBracketDepth++;
                return Tok_LeftBracket;
            case '\\':
                yyCh = getChar();
                yyCh = getChar(); // skip one character
                break;
            case ']':
                yyCh = getChar();
                if (yyNumPreprocessorSkipping == 0)
                    yyBracketDepth--;
                return Tok_RightBracket;
            case '{':
                yyCh = getChar();
                if (yyNumPreprocessorSkipping == 0)
                    yyBraceDepth++;
                return Tok_LeftBrace;
            case '}':
                yyCh = getChar();
                if (yyNumPreprocessorSkipping == 0)
                    yyBraceDepth--;
                return Tok_RightBrace;
            case '|':
                yyCh = getChar();
                if (yyCh == '|' || yyCh == '=')
                    yyCh = getChar();
                return Tok_SomeOperator;
            case '~':
                yyCh = getChar();
                return Tok_Tilde;
            case '@':
                yyCh = getChar();
                return Tok_At;
            default:
                // ### We should really prevent qdoc from looking at snippet files rather than
                // ### suppress warnings when reading them.
                if (yyNumPreprocessorSkipping == 0 && !yyTokLoc.fileName().endsWith(".qdoc")) {
                    yyTokLoc.warning(tr("Hostile character 0x%1 in C++ source")
                                      .arg((uchar)yyCh, 1, 16));
                }
                yyCh = getChar();
            }
        }
    }

    if (yyPreprocessorSkipping.count() > 1) {
        yyTokLoc.warning(tr("Expected #endif before end of file"));
        // clear it out or we get an infinite loop!
        while (!yyPreprocessorSkipping.isEmpty()) {
            popSkipping();
        }
    }

    strcpy(yyLex, "end-of-input");
    yyLexLen = strlen(yyLex);
    return Tok_Eoi;
}
示例#25
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();
            condition += yyCh;
            yyCh = getChar();
        }
        condition.replace(*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);
    return tok;
}
示例#26
0
void getNonBlank() {
    while(isspace(nextChar)) {
        getChar();
    }
}
示例#27
0
Token Lexer::lex()
{
	skipSpaces(); // skips the white space that it quite likely (indentation) infront of the Token

	Token currentToken;
	currentToken.type = tokNotSet; // not really needed
	currentToken.look = "";
	currentToken.value = 0;
	currentToken.start.row = row;
	currentToken.start.col = col;

	QChar currentChar = getChar();

	if ( inputStream->atEnd() )
	{
		kdDebug(0)<<"Lexer::lex(), got EOF."<<endl;
		currentToken.type = tokEOF;
		currentToken.look = "EOF";
		ungetChar(currentChar); // unget the currentChar and fix the row/col values
		return currentToken;
	}

	if (currentChar == '#')
	{
		while ( !inputStream->atEnd() && !(currentChar == '\x0a' || currentChar == '\n') )
			currentChar = getChar();
	}
	
	// if (currentChar.category() == QChar::Separator_Line) somehow doesnt work
	if (currentChar == '\x0a' || currentChar == '\n')
	{
		currentToken.type = tokEOL;
		currentToken.look = "EOL";
	}
	else if (currentChar.isLetter() || currentChar == '[' || currentChar == ']')
	{
		ungetChar(currentChar);
		// sets currentToken.look by reference, and set the currentToken.type to tokUnknown
		currentToken.type = getWord(currentToken.look);
		setTokenType(currentToken); // gets the actual tokenType
	}
	else if ( currentChar.isNumber() )
	{
		ungetChar(currentChar);
		// set currentToken.value/look by reference, and set the currentToken.type to tokNumber
		currentToken.type = getNumber(currentToken.value, currentToken.look);
	}
	else if (currentChar == '>')
	{
		currentChar = getChar();
		if (currentChar == '=')
		{
			currentToken.type = tokGe;
			currentToken.look = ">=";
		}
		else
		{
			ungetChar(currentChar);
			currentToken.type = tokGt;
			currentToken.look = ">";
		}
	}
	else if (currentChar == '<')
	{
		currentChar = getChar();
		if ( currentChar == '=' )
		{
			currentToken.type = tokLe;
			currentToken.look = "<=";
		}
		else
		{
			ungetChar(currentChar);
			currentToken.type = tokLt;
			currentToken.look = ">";
		}
	}
	else if (currentChar == '!')
	{
		currentChar = getChar();
		if (currentChar == '=')
		{
			currentToken.type = tokNe;
			currentToken.look = "!=";
		}
		else
		{
			ungetChar(currentChar);
			currentToken.type = tokNot;
			currentToken.look = "!";
		}
	}
	else if (currentChar == '=')
	{
		currentChar = getChar();
		if (currentChar == '=')
		{
			currentToken.type = tokEq;
			currentToken.look = "==";
		}
		else
		{
			ungetChar(currentChar);
			currentToken.type = tokAssign;
			currentToken.look = "=";
		}
	}
	else if (currentChar == '(')
	{
		currentToken.type = tokBraceOpen;
		currentToken.look = "(";
	}
	else if (currentChar == ')')
	{
		currentToken.type = tokBraceClose;
		currentToken.look = ")";
	}
	else if (currentChar == '+')
	{
		currentToken.type = tokPlus;
		currentToken.look = "+";
	}
	else if (currentChar == '-')
	{
		currentToken.type = tokMinus;
		currentToken.look = "-";
	}
	else if (currentChar == '*')
	{
		currentToken.type = tokMul;
		currentToken.look = "*";
	}
	else if (currentChar == '/')
	{
		currentToken.type = tokDev;
		currentToken.look = "/";
	}
	else if (currentChar == ',')
	{
		currentToken.type = tokComma;
		currentToken.look = ",";
	}
	else if (currentChar == '"')
	{
		getString(currentToken);
	}
	else
	{
		currentToken.type = tokUnknown;
		currentToken.look = currentChar;
	}
	
	currentToken.end.row = row;
	currentToken.end.col = col;
	return currentToken;
}
示例#28
0
SExpression * Reader::read()
{
    SExpression * ret = nil_symbol;
    
    ReaderChar val = eatWhitespace();

    if (atEnd())
    {
        return ret;
    }
    
    if (macroHint(val.chr))
    {
        uint32_t val2 = peek().chr;
        uint64_t key2 = ((uint64_t)val.chr << 32) | val2;
        uint64_t key1 = ((uint64_t)val.chr << 32) | INVALID_CHAR;
        if (macros[key2])
        {
            getChar(false);
            return macros[key2]->run(new List);
        }
        else if (macros[key1])
        {
            return macros[key1]->run(new List);
        }
        else
        {
            printf("Couldn't find macro for [%c][%c]!\n", val.chr, val2);
        }
    }
    
    if (tokenType(val.chr) == TOKEN_QUOTE)
    {
        String * str = new String;
        ret = str;
        ret->begin_line = line;
        ret->begin_column = column;
        do
        {
            uint32_t val = getChar().chr;
            if (atEnd())
            {
                printf("Got EOF in middle of string, %d\n", val);
            }
            if (tokenType(val) == TOKEN_QUOTE)
            {
                break;
            }
            str->append(val);
        } while (!atEnd());
        ret->end_line = line;
        ret->end_column = column;
    }
    else if ( (tokenType(val.chr) == TOKEN_NUMERIC) ||
              (tokenType(val.chr) == TOKEN_MINUS
               && tokenType(peek().chr) == TOKEN_NUMERIC) )
    {
        bool is_minus = false;
        bool is_hex = false;

        int save_line = line;
        int save_column = column;
        
        if (tokenType(val.chr) == TOKEN_MINUS)
        {
            is_minus = true;
            val = getChar();
        }
        if (val.chr == '0' && peek().chr == 'x')
        {
            is_hex = true;
            getChar();
        }
        int64_t count_val = val.chr - '0';
        do
        {
            val = getChar();
            
            if (val.chr < '0' || val.chr > '9')
            {
                if (is_hex && (val.chr >= 'a' && val.chr <= 'f'))
                {
                }
                else
                {
                    ret = new Number(is_minus ? -count_val : count_val);
                    ret->begin_line = save_line;
                    ret->begin_column = save_column;
                    ret->end_line = line;
                    ret->end_column = column;
                    reject(val);
                    break;
                }
            }

            if (is_hex)
            {
                if (val.chr >= 'a' && val.chr <= 'f')
                {
                    val.chr -= ('a' - 10);
                }
                else
                {
                    val.chr -= '0';
                }
                count_val *= 16;
                count_val += val.chr;
            }
            else
            {
                val.chr -= '0';
                count_val *= 10;
                count_val += val.chr;
            }

            if (atEnd())
            {
                ret = new Number(is_minus ? -count_val : count_val);
                ret->begin_line = save_line;
                ret->begin_column = save_column;
                ret->end_line = line;
                ret->end_column = column;
            }
        } while (!atEnd());
    } else if (tokenType(val.chr) == TOKEN_ALPHA) {
        String * str = new String;
        str->append(val.chr);
        Symbol * sym = new Symbol(str);
        ret = sym;
        ret->begin_line = line;
        ret->begin_column = column;
        do
        {
            ReaderChar val = getChar();
            if (atEnd() || (tokenType(val.chr) != TOKEN_ALPHA
                            && tokenType(val.chr) != TOKEN_MINUS &&
                            tokenType(val.chr) != TOKEN_NUMERIC))
            {
                reject(val);
                break;
            }
            str->append(val.chr);
        } while (!atEnd());
        ret->end_line = line;
        ret->end_column = column;
    } else if (tokenType(val.chr) == TOKEN_OPEN_BRACE) {
        List * list = new List;
        ret = list;
        ret->begin_line = line;
        ret->begin_column = column;
        do
        {
            ReaderChar next = eatWhitespace();
            
            if (atEnd())
            {
                printf("Got EOF in middle of list, %d\n", next.chr);
                break;
            }
            if (tokenType(next.chr) == TOKEN_CLOSE_BRACE)
            {
                break;
            }

            reject(next);
            SExpression * sep = read();
            list->contents.push_back(sep);
            
        } while(!atEnd());
        ret->end_line = line;
        ret->end_column = column;
    } else if (tokenType(val.chr) == TOKEN_COMMENT) {
        do {
            val = getChar();
        } while (tokenType(val.chr) != TOKEN_NEWLINE && !atEnd());
    } else {
        printf("Didn't expect %d %d!\n", val.chr, tokenType(val.chr));
    }
    
    return ret;
}
示例#29
0
ReaderChar Reader::getChar(bool trail)
{
    ReaderChar ret;
    
    if (charbuffer.size() > 0)
    {
        ret = charbuffer.front();
        charbuffer.pop_front();
        line = ret.line;
        column = ret.column;
        return ret;
    }
    
    ret.line = line;
    ret.column = column;
    
    unsigned char val;
    stream->read((char *)&val, 1);

    if (stream->eof())
    {
        is_eof = true;
        return ReaderChar();
    }

    ret.chr = val;
    
    if (!trail && val == '\n')
    {
        line++;
        column = 0;
    }
    else
    {
        column++;
    }
    
    if (!(val & 0x80))
        return ret;

    val &= ~0x80;
    int nobytes = 0;
    if (val & 0x40)
    {
        nobytes++;
        val &= ~0x40;
    }
    
    if (val & 0x20)
    {
        nobytes++;
        val &= ~0x20;
    }
    
    if (val & 0x10)
    {
        printf("Invalid UTF-8! Too many bytes\n");
        is_eof = true;
        return ReaderChar();
    }
    
    ret = ReaderChar(val,line,column);
    for (int loopc=0; loopc<nobytes; loopc++)
    {
        stream->read((char *)&val, 1);    
        if (stream->eof())
        {
            is_eof = true;
            return ReaderChar();
        }
    
        if ((!val & 0x80) || (val & 0x40))
        {
            printf("Invalid UTF-8! Wrong succeeding byte %x, nobytes %d\n", val, nobytes);
            is_eof = true;
            return ReaderChar();
        }
        
        ret.chr = ret.chr << 6;
        ret.chr |= val;
    }

    if (trail && (ret.chr < 0xdc00 || ret.chr > 0xdfff))
    {
        printf("Incorrect UTF-16 trail!\n");
        is_eof = true;
        return ReaderChar();
    }
    else if (ret.chr >= 0xd800 && ret.chr <= 0xdbff)
    {
            // This is a UTF-16 lead
        uint32_t next = getChar(true).chr;
        ret.chr -= 0xd800;
        ret.chr = ret.chr << 20;
        ret.chr += (next - 0xdc00);
        ret.chr += 0x10000;
    }

    return ret;
}
示例#30
0
int Lexan::getNextToken()
{
	int State = 0;
	char Char;
	int Exp = 0, ExpSign = 1; /* Velikost a znamenko exponentu */
	double DmsPos = 0.1; /* prave zpracovavany desetinny rad */

	while (true) {	
		Char = getChar();
		switch (State) 
		{
			case 0:
				if (Char == ' ' || Char == '\n' || Char == '\t' || Char == '\r')
					break;
				if (Char == ';')
					return (LEX_SEMICOLON);
				if (Char == '/') {
					State = 2;
					break;
				}				
				if (Char == '=') {
					State = 29;
					break;
				}			
				if (Char == '*') {
					State = 25;
					break;
				}
				if (Char == '(')
					return (LEX_LPA);
				if (Char == ')')
					return (LEX_RPA);							
				if (Char == '}')
					return (LEX_END);
				if (Char == '{')
					return (LEX_BEGIN);								
				if (isalpha(Char)) {
					identifierName = ""; 		//na zacatku je string nazvu prazdny			
					identifierName += Char;		//prvni znak identifikatoru
					State = 38;
					break;
				}				
				if (Char == '0') {
					intValue = 0;
					floatValue = 0.0;
					State = 7;
					break;
				}
				if (isdigit(Char)) 	//nula je chycana drive
				{ 
					intValue = Char - '0';
					floatValue = Char - '0';
					State = 11;
					break;
				}
				if (Char == '+')
				{
					State = 17;
					break;
				}
				if (Char == '-')
				{
					State = 20;
					break;
				}
				if (Char == '%')
				{
					State = 27;
					break;
				}
				if (Char == '!') {
					State = 31;
					break;
				}
				if (Char == '<')
				{
					State = 33;
					break;
				}
				if (Char == '>')
				{
					State = 35;
					break;
				}
				if (Char == '.') {
					floatValue = 0.0;
					DmsPos = 0.1;
					State = 16;
					break;
				}				
				if (Char == EOF)
					return (LEX_NULL);

				return (LEX_ERROR);								


			case 2:
				if (Char == '/') {	//jednoradkovy komentar
					State = 4;
					break;
				}
				if (Char == '=') {	//operator /=				
					return (LEX_DIVASSIGN);
				}
				if (Char == '*') {
					State = 5;
					break;
				}				

				ungetChar(Char);		//operator /
				return (LEX_DIV);


			case 4:
				if (Char == '\n') 
				{
					State = 0;
					break;
				}
				if (Char == EOF)
					return (LEX_ERROR); 
				break; 			//pokud by byl eof uvnitr
								// komentare zustava ve stavu 4

			case 5:
				if (Char == '*')
				{
					State = 6;
					break;
				}
				if(Char == LEX_EOF)			
					return (LEX_ERROR);				

				
			case 6:
				if (Char == '/') {	//konec komentare
					State = 0;
					break;
				}
				if (Char != '*')
				{
					State = 5;
					break;
				}
				
				break;			//state porad = 6 pri *


			case 7:
				if (isodigit(Char)) {
					State = 8;
					intValue = Char - '0';
					break;
				}
				if(Char == 'x' || Char == 'X')
				{				
					State = 9;
					break;
				}
				if(Char == '.')
				{
					State = 12;
					break;
				}
				if (Char == EOF)
					return (LEX_ERROR); 
				if(isalpha(Char))
					return (LEX_ERROR);

				ungetChar(Char);
				cout << "intValue = " << intValue << endl;
				return (LEX_INT);		//pokud neni ani okta ani hexa


			case 8:
				if (isodigit(Char)) {
					intValue = (intValue << 3) + (Char - '0');
					State = 8; 		//state bude porad 8
					break;
				}
				if(isalpha(Char))
					return (LEX_ERROR);

				ungetChar(Char);
				cout << "intValue = " << intValue << endl;
				return(LEX_INT);


			case 9:
				if(isxdigit(Char))
				{			
					Char = (char)toupper(Char);		
					intValue = (Char >= 'A') ? Char - 'A' + 10 : Char - '0';
					State = 10;
					break;
				}
				return(LEX_ERROR);


			case 10:				
				if (isxdigit(Char)) {
					Char = (char)toupper(Char); 
					intValue = (intValue << 4) + ((Char >= 'A') ? Char - 'A' + 10 : Char - '0');					
					break;
				}
			

			case 11:
				if(isdigit(Char))
				{
					intValue = intValue * 10 + Char - '0';
					floatValue = floatValue * 10.0 + Char - '0';
					break;
				}
				if(Char == '.')
				{
					State = 12;
					break;
				}
				if(isalpha(Char))
					return (LEX_ERROR);					

				ungetChar(Char); 		// nalezen integer 
				cout << "intValue = " << intValue << endl;
				return (LEX_INT);				
			

			case 12:
				if(isdigit(Char))
				{
					floatValue += DmsPos * (Char - '0'); 
					DmsPos /= 10.0; 	// pocitat intValue
					break;
				}
				if(Char == 'E' || Char == 'e')
				{	
					Exp = 0;
					ExpSign = 1;
					State = 13;
					break;
				}
				if(isalpha(Char))
					return (LEX_ERROR);

				ungetChar(Char); 		//desetinne cislo s jednim destinnym mistem
				cout << "floatValue = " << floatValue << endl;
				return (LEX_FLOAT);

			
			case 13:
				if(isdigit(Char))
				{
					Exp = Char - 0x30;
					State = 15;
					break;
				}
				if (Char == '+' || Char == '-') {
					ExpSign = (Char == '-') ? -1 : 1;						
					State = 14;
					break;
				}
				return (LEX_ERROR);


			case 14:
				if(isdigit(Char))
				{
					Exp = Char - 0x30;
					State = 15;
					break;
				}

				return (LEX_ERROR);

			
			case 15:
				if(isdigit(Char))
				{
					Exp = 10 * Exp + Char - 0x30; //dalsi cifry exponentu
					break;
				}
				
				ungetChar(Char);
				floatValue *= pow(10.0, Exp * ExpSign);
				cout << "floatValue = " << floatValue << endl;
				return (LEX_FLOAT);


			case 16:
				if(isdigit(Char))	
				{		
					floatValue = 0.1 * (Char - '0');
					DmsPos = 0.01; 			//priste jsou zpracovavany setiny
					State = 12;
					break;
				}


			case 17:
				if (Char == '=' || Char == '+') // ==
				{
					if(Char == '=')
					{
						State = 18;
						ungetChar(Char);
						break;
					}
					if (Char == '+')				
					{
						State = 19;
						ungetChar(Char);
						break;
					}
				}
				else
				{
					ungetChar(Char);
					return (LEX_ADD);
				}
			

			case 18:
				if(Char == '=')
					return LEX_ADDASSIGN; 
				else {
					ungetChar(Char); // jenom =
					return LEX_ADD;
				}
		

			case 19:			
				if(Char == '+')
					return (LEX_INCREMENT);
				else
				{	
					ungetChar(Char);
					return (LEX_ADD);
				}
			

			case 20:
				if(Char == '=' || Char == '-')
				{
					if(Char == '=')
					{
						State = 22;
						ungetChar(Char);
						break;
					
					}
					if(Char == '-')
					{
						State = 21;
						ungetChar(Char);
						break;
					}
				}
				else
				{
					ungetChar(Char);
					return (LEX_SUB);
				}


			case 21:
				if(Char == '-')				
					return (LEX_DECREMENT);
				else
				{
					ungetChar(Char);
					return (LEX_SUB);
				}	
			
			case 22:
				if(Char == '=')
					return (LEX_SUBASSIGN);
				else
				{
					ungetChar(Char);
					return (LEX_SUB);
				}				

			
			case 25:
				if(Char == '=')
					return (LEX_MULASSIGN);
				else
				{
					ungetChar(Char);
					return (LEX_MUL);	
				}

			case 27:
				if(Char == '=')
					return (LEX_MODASSIGN);
				else
				{	
					ungetChar(Char);
					return (LEX_MOD);
				}

			
			case 29:
				if(Char == '=')
					return (LEX_ISEQUAL);
				else
				{
					ungetChar(Char);
					return (LEX_ASSIGN);
				}
		
			case 31:
				if(Char == '=')
					return (LEX_ISNEQUAL);
				else
				{
					ungetChar(Char);
					return (LEX_EXCLAMATION);
				}

			case 33:
				if(Char == '=')
					return (LEX_LESS_EQU_THAN);
				else
				{
					ungetChar(Char);
					return (LEX_LESS_THAN);
				}

			case 35:
				if(Char == '=')
					return (LEX_GREATER_EQU_THAN);
				else
				{
					ungetChar(Char);
					return (LEX_GREATER_THAN);
				}
			
			case 38:
				if(isalpha(Char) || isdigit(Char))
				{
					identifierName += Char;				
					break;
				} else {				

					ungetChar(Char);
					map<int, string>::iterator i;

					for (i = keywords.begin(); i != keywords.end(); i++)
						if (identifierName.compare(i->second) == 0)
						{
							cout << "keyword: " << i->second << endl;
							return (i->first);
						}

					//identifikator nebyl nalezen v klicovych slovech
					cout << "identifier: " << identifierName << endl;
					return (LEX_IDENT);
				}

			default:
				throw "Lexical ERROR: unknown state";
				break;
		}
	}
}