bool UnprocessedStatement::getExtension(TokenList &extension) {
  TokenList::iterator i;
  int parentheses = 1;
  
  if (!isExtends())
    return false;

  i = getTokens()->begin(); 

  // &:extends(
  std::advance(i, 4);

  for (;i != getTokens()->end() && parentheses > 0; i++) {
    
    switch ((*i).type) {
    case Token::PAREN_OPEN:
      parentheses++;
      break;
    case Token::PAREN_CLOSED:
      parentheses--;
      break;
    default:
      break;
    }
    if (parentheses > 0)
      extension.push_back(*i);
  }

  if (parentheses > 0) {
    throw new ParseException("end of statement", ")", line, column, source);
  }
  return true;
}
Beispiel #2
0
TEST_F(LexerTest, EscapeSequences) {
  EXPECT_THROW(getTokens("\"cool string here\"  \\n "), Error);
  EXPECT_EQ(getTokens("\" \\n \"")[0], Token(TT::STRING, " \n ", defaultTrace));
  // TODO
  // EXPECT_EQ(getTokens("\" \\x0A \"")[0], Token(TT::STRING, " \n ", defaultTrace));
  // EXPECT_EQ(getTokens("\" \\075 \"")[0], Token(TT::STRING, " = ", defaultTrace));
  EXPECT_EQ(getTokens("\" \\\\ \"")[0], Token(TT::STRING, " \\ ", defaultTrace));
  EXPECT_EQ(getTokens("\" \\\" \"")[0], Token(TT::STRING, " \" ", defaultTrace));
}
Beispiel #3
0
QList<mapItem *> gameMap::getPlayerTokensOnArea(Area *a,player *p)
{
    QPolygonF areaPoly = viewer->sceneCoordinatesPolygon(a->polygon(),a->position());
    QList<mapItem *> findTokens = QList<mapItem *>();
    for(int i = 0; i < tokens->length(); i++)
    {

        if(areaPoly.containsPoint(getTokens()[i]->pos(),Qt::OddEvenFill) && getTokens()[i]->getOwnerPlayer()->getName() == p->getName())
            findTokens.append(getTokens()[i]);
    }
    return findTokens;
}
void UnprocessedStatement::process(Ruleset &r) {
  Extension extension;
  Mixin mixin;
  Declaration* declaration;

#ifdef WITH_LIBGLOG
  VLOG(2) << "Statement: " << getTokens()->toString();
#endif
  
  // process extends statement
  if (getExtension(extension.getTarget())) {
    extension.setExtension(r.getSelector());
    getLessRuleset()->getContext()->addExtension(extension);
    return;
  }
  
  mixin.setStylesheet(getLessRuleset()->getLessStylesheet());
  
  // process mixin
  if (mixin.parse(*getTokens()) &&
      mixin.insert(*r.getStylesheet(), *getLessRuleset()->getContext(),
                   &r, getLessRuleset())) {

  } else {
    declaration = r.createDeclaration();
    
    if (processDeclaration(declaration)) {
    
#ifdef WITH_LIBGLOG
      VLOG(2) << "Declaration: " <<
        declaration->getProperty() << ": " << declaration->getValue().toString();
#endif
    
      getLessRuleset()->getContext()->processValue(declaration->getValue());

#ifdef WITH_LIBGLOG
      VLOG(2) << "Processed declaration: " <<
        declaration->getProperty() << ": " << declaration->getValue().toString();
#endif
    
    } else {
      r.deleteDeclaration(*declaration);
      throw new ParseException(getTokens()->toString(),
                               "variable, mixin or declaration.",
                               line, column, source);
    }
  }

#ifdef WITH_LIBGLOG
  VLOG(3) << "Statement done";
#endif
}
Beispiel #5
0
std::string StringReader::word(bool truncateEnd)
{
    std::vector<std::string> stop_chars;
    stop_chars.push_back(" ");
    stop_chars.push_back("\n");
    stop_chars.push_back("\t");
    

    std::string result = getTokens(stop_chars, truncateEnd);
    while (result == " " || result == "\n" || result == "\t")
    {
        result = getTokens(stop_chars, truncateEnd);
    }
    return(result);
}
Beispiel #6
0
void CCQLParser::check_index(IN std::string input, OUT Token *token)
{
    std::vector<std::string> tokens = getTokens(input, "[");

    if (tokens.size() == 2)
    {
        if (tolower(tokens.at(1)) == "all]")
        {
            token->name = tokens.at(0);
            token->number = INDEX_ALL;

        }
        else if (tolower(tokens.at(1)) == "this]")
        {
            token->name = tokens.at(0);
            token->number = INDEX_THIS;

        }
        else
        {
            int num = atoi(tokens.at(1).c_str());
            token->name = tokens.at(0);
            token->number = num;
        }
    }
}
Beispiel #7
0
int parserLine(struct shell_state *state, const char *line)
{
	char **argv = NULL;
	int argc = 0;
	struct function *fct = NULL;

	argc = getTokens(line, &argv);
	argc = replaceTokens(argc, &argv, state);

	if((fct = searchFunction(state->cmds, argv[0])) != NULL)
	{
		state->last_ret_value = fct->f(argc, argv);

		for(; argc > 0; argc--)
			free(argv[argc-1]);

		return 0;
	}
	else
	{
		printf("%s : unknown filename or command.\n", argv[0]);
		return -1;	
	}

	return 0;
}
/*This main calls the getTokens to get an Array oTokens of Tokens objects
defined in the token ADT. The main later evaluates the expression of the
tokens by calling evaluate and returns the result. The Input that is being
tokenized is the command line. We are assuming tokens are separated by
spaces. */
int main(int argc, char *argv[])
{
    int i, len;
    if (argc < 4) {
        fprintf(stderr,"not enough arguments");
        return 0;
    }
    for (i = 1; i < argc; i++) len += strlen(argv[i]);
    char* pcLine = malloc(len + argc);
    strcpy(pcLine, argv[1]);
    for (i = 2; i < argc; i++) {
        strcat(pcLine, " ");
        strcat(pcLine, argv[i]);
    }
    /*printf("%s\n", pcLine);*/
    Token_T* oTokens = getTokens(pcLine, argc - 1);
    /*printf("\n");*/
    if (oTokens == NULL) return 0;
    else {
        evaluate(oTokens, argc-1);
        /*tokenize_printTokens(oTokens, argc - 1);*/
        tokenize_freeTokens(oTokens, argc - 1);
        free(oTokens);
    }
    free(pcLine);
    return 0;
}
//------------------------------------------------------------------------
//--- JetCorrectorParameters::Record constructor -------------------------
//--- reads the member variables from a string ---------------------------
//------------------------------------------------------------------------
JetCorrectorParameters::Record::Record(const std::string& fLine,unsigned fNvar) : mMin(0),mMax(0)
{
  mNvar = fNvar;
  // quckly parse the line
  std::vector<std::string> tokens = getTokens(fLine);
  if (!tokens.empty())
    {
      if (tokens.size() < 3)
        {
          std::stringstream sserr;
	  sserr<<"(line "<<fLine<<"): "<<"three tokens expected, "<<tokens.size()<<" provided.";
          handleError("JetCorrectorParameters::Record",sserr.str());
        }
      for(unsigned i=0;i<mNvar;i++)
        {
          mMin.push_back(getFloat(tokens[i*mNvar]));
          mMax.push_back(getFloat(tokens[i*mNvar+1]));
        }
      unsigned nParam = getUnsigned(tokens[2*mNvar]);
      if (nParam != tokens.size()-(2*mNvar+1))
        {
          std::stringstream sserr;
	  sserr<<"(line "<<fLine<<"): "<<tokens.size()-(2*mNvar+1)<<" parameters, but nParam="<<nParam<<".";
          handleError("JetCorrectorParameters::Record",sserr.str());
        }
      for (unsigned i = (2*mNvar+1); i < tokens.size(); ++i)
        mParameters.push_back(getFloat(tokens[i]));
    }
}
Beispiel #10
0
int loadData(PhoneBook **b, char *fileName)
{
  FILE *f;
  int i;
  char buffer[500];
  char tokens[2][200];
  /* count the number of lines in the file */
  int nline = countLine(fileName);
  /* allocate memory for the phonebook */
  PhoneBook *book =  (PhoneBook *) malloc(sizeof(PhoneBook)*nline);

  f = fopen(fileName, "r");
  for(i = 0; i< nline; i++){
    fgets(buffer, 500, f);
    getTokens(buffer, tokens, '-');
    strcpy(book[i].name, tokens[0]);
    strcpy(book[i].phone, tokens[1]);
  }
  
  fclose(f);

  *b = book;
  
  return nline;
}
Beispiel #11
0
void gameMap::removePlayerTokensArea(Area *a, player *p,int nbIteration)
{
    QPolygonF areaPoly = viewer->sceneCoordinatesPolygon(a->polygon(),a->position());

    for(int j = 0; j < nbIteration; j++)
    {
    for(int i = 0; i < tokens->length(); i++)
    {

        if(areaPoly.containsPoint(getTokens()[i]->pos(),Qt::OddEvenFill) && getTokens()[i]->getOwnerPlayer()->getName() == p->getName())
        {
           viewer->scene()->removeItem(tokens->at(i));
            tokens->removeAt(i);
        }
    }
    }
}
Beispiel #12
0
/*
 * Read the reserved IP addresses from configuration file and put them into array.
 * Returns the number of IP address read.
 */
int getReservedAddr(char reservedMacAddr[][MAX_TOKEN_SIZE], char reservedIpAddr[][MAX_TOKEN_SIZE])
{
#define BUFFER_SIZE     2*1024
    int numReservedMac=0, numReservedIp=0;
    char buffer[BUFFER_SIZE];      /*  modified pling 10/04/2007, to allow max 64 reserved IP */
    FILE *in;
    
	if (!(in = fopen("/tmp/udhcpd_resrv.conf", "r"))) 
    {
		LOG(LOG_ERR, "unable to open config file: /tmp/udhcpd_resrv.conf");
		return 0;
	}    
    
    /*get ip*/
    memset(buffer, 0, BUFFER_SIZE);
    if ( fgets(buffer, BUFFER_SIZE, in) )
    {
        numReservedIp = getTokens(buffer, " ", reservedIpAddr, MAX_RESERVED_IP);
        //LOG(LOG_INFO, "# of reserved ip: %d\n", numReservedIp);
    }
    else
    {
        //LOG(LOG_ERR, "reserved ip not found.\n");
        return 0;
    }

    /*get mac*/
    memset(buffer, 0, BUFFER_SIZE);
    if ( fgets(buffer, BUFFER_SIZE, in) )
    {
        numReservedMac = getTokens(buffer, " ", reservedMacAddr, MAX_RESERVED_MAC);
        //LOG(LOG_INFO, "# of reserved mac: %d\n", numReservedIp);
    }
    else
    {
        //LOG(LOG_ERR, "reserved mac not found.\n");
        return 0;
    }

    if (numReservedMac != numReservedIp)
    {
        //LOG(LOG_INFO, "WARNING! Reserved IP inconsistency!\n");
    }

    return (numReservedMac<numReservedIp ? numReservedMac:numReservedIp);
}
Beispiel #13
0
void UnprocessedStatement::insert(Stylesheet &s) {
  Mixin mixin;
  mixin.setStylesheet(getLessRuleset()->getLessStylesheet());
  
  // process mixin
  if (mixin.parse(*getTokens()))
    mixin.insert(s, *getLessRuleset()->getContext(),
                 NULL, getLessRuleset());
}
Beispiel #14
0
bool UnprocessedStatement::isExtends() {
  TokenList::iterator i = getTokens()->begin();
  
  return ((*i) == "&" &&
          (*++i).type == Token::COLON &&
          (*++i).type == Token::IDENTIFIER &&
          (*i) == "extend" &&
          (*++i).type == Token::PAREN_OPEN);
}
Beispiel #15
0
TEST_F(LexerTest, Expression) {
  getTokens("(-12 + -3) / 1.5 >> 1");
  EXPECT_EQ(lx[0], Token(TT::PAREN_LEFT, "(", defaultTrace));
  EXPECT_EQ(lx[1], Token(TT::OPERATOR, 24, defaultTrace));
  EXPECT_EQ(lx[2], Token(TT::INTEGER, "12", defaultTrace));
  EXPECT_EQ(lx[5], Token(TT::INTEGER, "3", defaultTrace));
  EXPECT_EQ(lx[6], Token(TT::PAREN_RIGHT, ")", defaultTrace));
  EXPECT_EQ(lx[8], Token(TT::FLOAT, "1.5", defaultTrace));
  EXPECT_EQ(lx[10], Token(TT::INTEGER, "1", defaultTrace));
}
int readOption(char* line)
//
//  Input:   line = line of input data
//  Output:  returns error code
//  Purpose: reads an input line containing a project option.
//
{
    Ntokens = getTokens(line);
    if ( Ntokens < 2 ) return 0;
    return project_readOption(Tok[0], Tok[1]);
}
Beispiel #17
0
int main(int argc, char *argv[]) {
    int x;
    int y = 0;
    int size = 0;
    char line[MAX_LINE];
    char *token;
    int id;
    pthread_attr_t attr;
    pthread_mutex_t *mutex;
    pthread_t threadID[MAX_THREADS];
    trace processTable[MAX_THREADS];
    struct arg_struct args;  
 
    /*Verifica entrada*/
    if (argc < 4) {
    	printf("USAGE: ./ep1 x(1 to 6) traceFile resultFile -d(optional)\n");
    	exit(0);
    }
    id = atoi(argv[1]);

    FILE *trace;
    if ((trace = fopen(argv[2],"r")) == NULL) {
       	printf("arquivo:%s nao encontrado\n",argv[2]);
        exit(0);
    }
	/*---------------*/
  /*Ler o arquivo trace e monta a tabela de processo*/
  for (x = 0; x < MAX_LINE; x++)
    	line[x] = 0;
  while (1) {
       if (fgets(line, 100, trace) == NULL)
          break;
       size++;
       getTokens(line, &processTable[size -1]);
  }
  /*---------------------------------------------------*/
  

  switch(id) {
    /*Escalanador first in first out*/
    case 1:
    /*Atributos inicias*/
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    /*Inicializa todos os jobs*/
    jobs_init(processTable,threadID, size, &attr);
    pthread_attr_destroy(&attr);
    break;
  }  
   
  return (0);
 
}
Beispiel #18
0
List *parse_expressions(FILE *stream){
   List *tokens = getTokens(stream);
   List *tokens2 = tokens;
   List *expressions = NULL;
   while (tokens2 != NULL){
       expressions = cons(consume_expression(&tokens2), expressions);
   }
   List *uncompiled_expressions = reverse_list(expressions);
   free_list(expressions, nop_free_fn);
   free_list(tokens, (free_fn_ptr)free_token);
   return uncompiled_expressions;
}
Beispiel #19
0
ASMParser::ASMParser(string filename)
  // Specify a text file containing MIPS assembly instructions. Function
  // checks syntactic correctness /f file and creates a list of Instructions.
{
  Instruction i;
  myFormatCorrect = true;

  myLabelAddress = 0x400000;

  ifstream in;
  in.open(filename.c_str());
  if(in.bad()){
    myFormatCorrect = false;
  }
  else{
    string line;
    while( getline(in, line)){
      string opcode("");
      string operand[80];
      int operand_count = 0;

      getTokens(line, opcode, operand, operand_count);

      if(opcode.length() == 0 && operand_count != 0){
		// No opcode but operands

		myFormatCorrect = false;
		break;
      }

      Opcode o = opcodes.getOpcode(opcode);      
      if(o == UNDEFINED){
		// invalid opcode specified
		myFormatCorrect = false;
		break;
      }

      bool success = getOperands(i, o, operand, operand_count);
      if(!success){
		myFormatCorrect = false;
		break;
      }

      string encoding = encode(i);
      i.setEncoding(encoding);

      myInstructions.push_back(i);

    }
  }

  myIndex = 0;
}
Beispiel #20
0
TEST_F(LexerTest, Operators) {
  EXPECT_EQ(getTokens("!=")[0], Token(TT::OPERATOR, 1, defaultTrace));
  EXPECT_EQ(getTokens("1 + 1")[1], Token(TT::OPERATOR, 31, defaultTrace));
  EXPECT_EQ(getTokens("+ 1")[0], Token(TT::OPERATOR, 25, defaultTrace));
  EXPECT_EQ(getTokens("++1")[0], Token(TT::OPERATOR, 23, defaultTrace));
  EXPECT_EQ(getTokens("1++ + 2")[1], Token(TT::OPERATOR, 20, defaultTrace));
  EXPECT_EQ(lx[2], Token(TT::OPERATOR, 31, defaultTrace));
  EXPECT_EQ(getTokens("1++ + ++2")[3], Token(TT::OPERATOR, 23, defaultTrace));
  EXPECT_EQ(lx[2], Token(TT::OPERATOR, 31, defaultTrace));
}
Beispiel #21
0
QSet<QString> SCsParser::getIdentifier(const QString &text)
{
	QSet<QString> idtf;

 	QVector<SCsParserToken> token = getTokens(text);
 	QVector<SCsParserToken>::iterator it = token.begin();
	while (it!=token.end())
	{
		if(it->tokenType() == NAME)
		{
			idtf.insert(it->tokenText());
		}
		++it;
	}

	return idtf;
}
Beispiel #22
0
int main(int argc, char *argv[]){
	char buffer[LINE_BUFFER];
	char **commandArgv;
	int commandArgc;
    printf("# Image compressor for SCC0261 - Multimedia.\n");
    printf("# Type 'help' for available commands.\n");
	//Sempre esperando por novos comandos
    while(1){
        //Indica ao usuario que o terminal esta pronto para receber input
        printf("potato> ");
        //le a linha inteira, considerada um comando, e a processa.
        readLine(buffer,LINE_BUFFER);
        commandArgv = getTokens(&commandArgc, buffer);

        if(commandArgc == 0) continue;
        if(commandArgv[0][0] == '#') continue;

        if(strcmp(commandArgv[0],"help") == 0){
            help(commandArgc, commandArgv);
        } else if(strcmp(commandArgv[0],"quit") == 0){
            break;
        } else if(strcmp(commandArgv[0],"q") == 0){
            break;
        } else if(strcmp(commandArgv[0],"compress") == 0){
            compressInput(commandArgc, commandArgv);
        } else if(strcmp(commandArgv[0],"decompress") == 0){
            decompressInput(commandArgc, commandArgv);
        } else {
            printf("Shell: Command '%s' not found. See 'help' for available commands.\n",commandArgv[0]);
        }



        if(debug){
            int i;
            for(i = 0; i < commandArgc; i++){
                printf("{%s}\n", commandArgv[i]);
            }
        }
        free(commandArgv);
    }
    free(commandArgv);
    return EXIT_SUCCESS;
}
/* get up to `limit' whitespace separated tokens from `str *string' */
static int
getStrTokens(str *string, str *tokens, int limit)
{
    int count;
    char c;

    if (!string || !string->s) {
        return 0;
    }

    c = string->s[string->len];
    string->s[string->len] = 0;

    count = getTokens(string->s, tokens, limit);

    string->s[string->len] = c;

    return count;
}
Beispiel #24
0
void modifyShader(std::string& shader)
{
    std::istringstream shaderStream(shader);
    std::string line;
    std::getline(shaderStream, line);
    std::string mod_shader("#version 300 es\n");

    std::unordered_map<std::string, int>::iterator it;
    std::unordered_map<std::string, int>::iterator it1;
    while (std::getline(shaderStream, line))
    {
        if (line.find("GL_ARB_separate_shader_objects") != std::string::npos ||
            line.find("GL_ARB_shading_language_420pack") != std::string::npos)
            continue;

        std::unordered_map<std::string, int> tokens;
        getTokens(tokens, line);

        if ((it = tokens.find("uniform")) != tokens.end() && checkSamplers(tokens)){
            int layout_pos = tokens["layout"];
            mod_shader += ((layout_pos > 0) ? line.substr(0, layout_pos) : "") + line.substr(it->second) + "\n";

        }
        else if ((it = tokens.find("layout")) != tokens.end() && tokens.find("uniform")==tokens.end() && tokens.find("num_views") == tokens.end()) {
            it1 = tokens.find("in");
            if (it1 == tokens.end())
                it1 = tokens.find("out");
            int pos = it->second;

            if(it1 != tokens.end())
            mod_shader += ((pos > 0) ? line.substr(0, pos) : "") + line.substr(it1->second) + "\n";
        }
        else
            {
            mod_shader += line + "\n";
        }
    }
    shader = mod_shader;
}
Beispiel #25
0
void ParseTreeLablerForm::setUpTree(char * labelMapFile)
{
    std::ifstream fileI;
    std::string line;
    standardModel = new QStandardItemModel ;
    rootNode = standardModel->invisibleRootItem();

    set<int> segsWithLabel;
    fileI.open(labelMapFile);
    if (fileI.is_open())
    {
        while (fileI.good())
        {
            getline(fileI, line); 
            if (line.size() == 0)
                break;

            vector<string> toks;
            getTokens(line, toks);
            int segNum=lexical_cast<int>(toks.at(1));
            label_mapping_orig[segNum] = toks.at(0);
            segsWithLabel.insert(segNum);
            string name="seg_"+lexical_cast<string>(segNum)+"_"+toks.at(0);
            QStandardItem *item = new QStandardItem(name.data()); 
            nameToTreeNode[name]=item;
            
            cout<<item->text().toUtf8().constData()<<endl;
            rootNode->appendRow(item);
        }
            widget.treeView->setModel(standardModel);
    }
    else
    {
        cout << "could not open the gt LabelMap file you specified ..exiting\n";
        exit(-1);
    }
    
}
Beispiel #26
0
std::vector<std::string> CCQLParser::tokenize(IN const std::string &input)
{
    std::vector<std::string> temp;
    temp.push_back(",");
    temp.push_back(" ");

    std::vector<std::string> tokens_temp;
    std::string arrage_query = input;
    arrage_query = check_Predicate(arrage_query);
    for (unsigned int i = 0 ; i < temp.size(); i++)
    {

        tokens_temp.clear();
        tokens_temp = getTokens(arrage_query, temp.at(i));
        arrage_query = "";
        for (unsigned int j = 0  ; j < tokens_temp.size() ; j++)
        {
            arrage_query += tokens_temp.at(j) + " ";
            //cout << "element = " << tokens_temp.at(j) << endl;
        }
    }
    return tokens_temp;
}
//------------------------------------------------------------------------
//--- JetCorrectorParameters::Definitions constructor --------------------
//--- reads the member variables from a string ---------------------------
//------------------------------------------------------------------------
JetCorrectorParameters::Definitions::Definitions(const std::string& fLine)
{
  std::vector<std::string> tokens = getTokens(fLine);
  if (!tokens.empty())
    {
      if (tokens.size() < 6)
        {
          std::stringstream sserr;
          sserr<<"(line "<<fLine<<"): less than 6 expected tokens:"<<tokens.size();
          handleError("JetCorrectorParameters::Definitions",sserr.str());
        }
      unsigned nvar = getUnsigned(tokens[0]);
      unsigned npar = getUnsigned(tokens[nvar+1]);
      for(unsigned i=0;i<nvar;i++)
        mBinVar.push_back(tokens[i+1]);
      for(unsigned i=0;i<npar;i++)
        mParVar.push_back(tokens[nvar+2+i]);
      mFormula = tokens[npar+nvar+2];
      std::string ss = tokens[npar+nvar+3];
      if (ss == "Response")
        mIsResponse = true;
      else if (ss == "Correction")
        mIsResponse = false;
      else if (ss == "Resolution")
	mIsResponse = false;
      else if (ss.find("PAR")==0)
	mIsResponse = false;
      else
        {
          std::stringstream sserr;
          sserr<<"unknown option ("<<ss<<")";
          handleError("JetCorrectorParameters::Definitions",sserr.str());
        }
      mLevel = tokens[npar+nvar+4];
    }
}
Beispiel #28
0
	void WebUser::setPermissions(const string& aStr) noexcept {
		auto lst = StringTokenizer<string>(aStr, ',');
		setPermissions(lst.getTokens());
	}
Beispiel #29
0
  /**
   *
   * Read one species definition in a NASA9 string.
   *
   */
  void CKParser::readNASA9ThermoRecord(Species& sp) {
    string s;
    string numstr;
    double cf;
    // Set to the NASA9 polynomial format
    sp.thermoFormatType = 1;

    // look for line 1, but if a keyword is found first or the end of
    // the file is reached, return "<END>" as the species name
    string comment;

    // Name of the species
    string nameid;
    vector<string> toks;
    int nToks = 0;

    // Loop forward until we get to the next nonempty line.
    do {
      getCKLine(s, comment);
      if (isKeyword(s) || match(s, "<EOF>")) {
	sp.name = "<END>";
	putCKLine(s, comment);
	return;
      }

      // The first 18 spaces are devoted to the name of the species
      string nameid = s.substr(0,18);
      getTokens(nameid, static_cast<int>(nameid.size()), toks);
      nToks = toks.size();
    }  while (nToks == 0);

    //------------- line 1 ---------------------------
    //  Everything after the first 18 spaces is a comment.
    int nt = s.size();
    sp.m_commentsRef = s.substr(18, nt-18);

    // Parse the species name
    sp.name = toks[0];
    sp.id = "";
    if (nToks > 1) {
      throw CK_SyntaxError(*m_log,
			   "Illegal number of tokens for string name", m_line);
    }
    checkSpeciesName(sp.name);


    //------------- line 2 ---------------------------

    getCKLine(s, comment);
    if (s.size() < 79) {
      throw CK_SyntaxError(*m_log,
			   "Size of second line is too small", m_line);
    }
    // Read the number of temperature regions.
    string sN = s.substr(0,2);
    sp.nTempRegions = de_atoi(*m_log, sN);

    string refDataCode = s.substr(3,6);

    // elemental composition (first 5 elements)
    for (int i = 0; i < 5; i++) {
      string elementSym = "";
      int iloc = 10 + 8*i;
      if (s[iloc] != ' ') {
	if (s[iloc+1] != ' ') {
	  elementSym = s.substr(iloc,2);
	} else { 
	  elementSym = s.substr(iloc,1);
	}
      } else if (s[iloc+1] != ' ') {
	elementSym = s.substr(iloc+1,1);
      }
      double atoms = de_atof(s.substr(iloc+2,6));
      addElement(elementSym, atoms, sp, *m_log);
    }
    
  
    // single-character phase descriptor
    sp.phase = s.substr(50,2);

    // Molecular weight in gm per gmol
    string molecWeight = s.substr(52, 13);

    // Heat of formation at 298.15 K in J / gmol
    string Hf298_Jgmol = s.substr(65, 15);

    vector_fp *coeffs_ptr;
    for (int i = 0; i < sp.nTempRegions; i++) {

      coeffs_ptr = new vector_fp(9);
      vector_fp &coeffs = *coeffs_ptr;

      //------------- line 3 ---------------------------
      getCKLine(s, comment);
      if (s.size() < 79) {
	throw CK_SyntaxError(*m_log,
			     "Size of third line is too small", m_line);
      }

      string sTlow = s.substr(0, 11);
      double tLow = de_atof(sTlow);

      string sTHigh = s.substr(11, 11);
      double tHigh = de_atof(sTHigh);

      string sNCoeff = s.substr(22, 1);
      int nCoeff = de_atoi(*m_log, sNCoeff);
      if (nCoeff != 7) {
	throw CK_SyntaxError(*m_log, "ncoeff ne 7", m_line);
      }

      string sTCoeff1 = s.substr(24, 5);
      double TCoeff1 = de_atof(sTCoeff1);
      if (TCoeff1 != -2.0) {
	throw CK_SyntaxError(*m_log, "TCoeff1 ne -2.0", m_line);
      }

      string sTCoeff2 = s.substr(29, 5);
      double TCoeff2 = de_atof(sTCoeff2);
      if (TCoeff2 != -1.0) {
	throw CK_SyntaxError(*m_log, "TCoeff2 ne -1.0", m_line);
      }

      string sTCoeff3 = s.substr(34, 5);
      double TCoeff3 = de_atof(sTCoeff3);
      if (TCoeff3 != 0.0) {
	throw CK_SyntaxError(*m_log, "TCoeff3 ne 0.0", m_line);
      }

      string sTCoeff4 = s.substr(39, 5);
      double TCoeff4 = de_atof(sTCoeff4);
      if (TCoeff4 != 1.0) {
	throw CK_SyntaxError(*m_log, "TCoeff4 ne 1.0", m_line);
      }

      string sTCoeff5 = s.substr(44, 5);
      double TCoeff5 = de_atof(sTCoeff5);
      if (TCoeff5 != 2.0) {
	throw CK_SyntaxError(*m_log, "TCoeff5 ne 2.0", m_line);
      }

      string sTCoeff6 = s.substr(49, 5);
      double TCoeff6 = de_atof(sTCoeff6);
      if (TCoeff6 != 3.0) {
	throw CK_SyntaxError(*m_log, "TCoeff6 ne 3.0", m_line);
      }

      string sTCoeff7 = s.substr(54, 5);
      double TCoeff7 = de_atof(sTCoeff7);
      if (TCoeff7 != 4.0) {
	throw CK_SyntaxError(*m_log, "TCoeff7 ne 4.0", m_line);
      }

      string sHf298mHF0 = s.substr(65, 15);
      
      //------------- line 4 ---------------------------
      getCKLine(s, comment);
      if (s.size() < 79) {
	throw CK_SyntaxError(*m_log,
			     "Size of third line is too small", m_line);
      }

      numstr = s.substr(0, 16);
      cf = getNumberFromString(numstr);
      if (cf == UNDEF) illegalNumber(*m_log, numstr, m_line);
      coeffs[0] = cf;

      numstr = s.substr(16, 16);
      cf = getNumberFromString(numstr);
      if (cf == UNDEF) illegalNumber(*m_log, numstr, m_line);
      coeffs[1] = cf;

      numstr = s.substr(32, 16);
      cf = getNumberFromString(numstr);
      if (cf == UNDEF) illegalNumber(*m_log, numstr, m_line);
      coeffs[2] = cf;

      numstr = s.substr(48, 16);
      cf = getNumberFromString(numstr);
      if (cf == UNDEF) illegalNumber(*m_log, numstr, m_line);
      coeffs[3] = cf;

      numstr = s.substr(64, 16);
      cf = getNumberFromString(numstr);
      if (cf == UNDEF) illegalNumber(*m_log, numstr, m_line);
      coeffs[4] = cf;

      //------------- line 5 ---------------------------
      getCKLine(s, comment);
      if (s.size() < 79) {
	throw CK_SyntaxError(*m_log,
			     "Size of fourth line is too small", m_line);
      }

      numstr = s.substr(0, 16);
      cf = getNumberFromString(numstr);
      if (cf == UNDEF) illegalNumber(*m_log, numstr, m_line);
      coeffs[5] = cf;

      numstr = s.substr(16, 16);
      cf = getNumberFromString(numstr);
      if (cf == UNDEF) illegalNumber(*m_log, numstr, m_line);
      coeffs[6] = cf;

      numstr = s.substr(48, 16);
      cf = getNumberFromString(numstr);
      if (cf == UNDEF) illegalNumber(*m_log, numstr, m_line);
      coeffs[7] = cf;

      numstr = s.substr(64, 16);
      cf = getNumberFromString(numstr);
      if (cf == UNDEF) illegalNumber(*m_log, numstr, m_line);
      coeffs[8] = cf;

      // Store the coefficients.
      sp.minTemps.push_back(tLow);
      sp.maxTemps.push_back(tHigh);

      sp.region_coeffs.push_back(coeffs_ptr);

    }

    sp.valid = 1;
  }
Beispiel #30
0
  /**
   *
   * Read species data from THERMO section records. 
   * 
   * @param names        List of species names (input).
   * @param species      Table of species objects holding data from records
   *                     in THERMO section (output). 
   * @param temp         Devault vector of temperature region boundaries
   *                     There are one more temperatures than there are
   *                     temperature regions.
   * @param allowExtThermoData   True if 'THERMO' specified, false if 
   *                             'THERMO ALL' specified.
   *
   * @return            True, if the THERMO section exists and the species
   *                    have all been successfully processed. False, if
   *                    the THERMO section doesn't exist or there were
   *                    additional problems.
   */
  bool CKParser::readNASA9ThermoSection(std::vector<string>& names, 
					speciesTable& species, vector_fp& temp, 
					int& optionFlag, std::ostream& log) {
    // String buffer for lines
    string s;
    vector<string> toks;
    string defaultDate="";
    int nreg = 2;
    int i;

    int nsp = static_cast<int>(names.size());

    // Comment string
    string comment;


    // if "THERMO ALL" specified, or if optionFlag is set to HasTempRange,
    // then the next line must be the default temperatures for the database.
    //
    //  This line will have nreg+2 tokens on it
    //    The last token is a date.
    if (0) {
      if (optionFlag == NoThermoDatabase || optionFlag == HasTempRange) {
	getCKLine(s, comment);
	getTokens(s, static_cast<int>(s.size()), toks);
	nreg = toks.size();
	if (nreg >= 1) {
	  temp.resize(nreg+1);
	  for (i = 0; i <= nreg; i++) {
	    temp[i] = de_atof(toks[i]);
	  }
	  defaultDate = toks[nreg+1];
	}
      
	if (verbose) {
	  log.flags(ios::showpoint | ios::fixed);
	  log.precision(2);
	  log << endl << " Default # of temperature regions: " << nreg << endl;
	  log << "          ";
	  for (i = 0; i <= nreg; i++) {
	    log << temp[i] << "  ";
	  }
	  log << endl;
	}
	checkNASA9Temps(log, temp);
      }
    }
    
    // Check to see that we expect to be reading a NASA9 formatted file
    if (!m_nasa9fmt) {
      throw CK_SyntaxError(log, 
			   "In NASA9 parser. However, we expect a different file format",
			   -1);
    }

    // now read in all species records that have names in list 'names'

    bool getAllSpecies = (nsp > 0 && match(names[0], "<ALL>"));
    if (getAllSpecies) names.clear();

    // Map between the number of times a species name appears in the database
    map<string, int> dup; // used to check for duplicate THERMO records
    bool already_read;

    while (1 > 0) {
      // If we don't have any more species to read, break
      if (nsp == 0) break;
      already_read = false;

      // Read a new species record from the section
      Species spec;
      readNASA9ThermoRecord(spec);

      // we signal the end of the section by putting <END> as a
      // species name. Break if you find the end of the section.
      if (spec.name == "<END>") {
	break;
      }
        
      // check for duplicate thermo data
      if (dup[spec.name] == 2) {
	log << "Warning: more than one THERMO record for "
	    << "species " << spec.name << endl;
	log << "Record at line " << m_line 
	    << " of " << m_ckfilename << " ignored." << endl;
	already_read = true;
      }
      // Set the record in the map to 2 to create a signal for the
      // next time.
      dup[spec.name] = 2;

      // Check to see whether we need this particlar species name
      if (!already_read && (getAllSpecies 
			    || (find(names.begin(), names.end(), spec.name) 
				< names.end()))) {

	// Add the species object to the map. Note we are
	// doing a copy constructor here, so we create a
	// lasting entry.
	species[spec.name] = spec;

	if (verbose) {        
	  log << endl << "found species " << spec.name;
	  log << " at line " << m_line 
	      << " of " << m_ckfilename;
	  writeSpeciesData(log, spec);
	}
	//checkTemps(log, spec.tlow, spec.tmid, spec.thigh);
	if (getAllSpecies) {
	  names.push_back(spec.name);
	  nsp = static_cast<int>(names.size());
	}
	else
	  nsp--;
      }
    }
    return true;
  }