Esempio n. 1
0
int main(int argumentCount, char** argumentVector) {
    if (argumentCount < 2) {
        std::cerr
            << "Usage: "
            << argumentVector[0]
            << " <(multi)PolygonFile>, ..."
            << std::endl;
        return 1;
    }
    
    std::cerr << "Loading " << argumentVector[1] << "..." << std::endl;
    std::string polygonString(readFile(argumentVector[1]));
    TokenStream tokenStream(polygonString);
    Parser parser(tokenStream);
    Polygon_set polygon = parser.parsePolygonSetDefinition();
    
    for (int i = 2; i < argumentCount; ++i) {
        std::cerr << "Loading " << argumentVector[i] << "..." << std::endl;
        std::string polygonString2(readFile(argumentVector[i]));
        TokenStream tokenStream2(polygonString2);
        Parser parser2(tokenStream2);
        Polygon_set polygon2 = parser2.parsePolygonSetDefinition();
        polygon.intersection(polygon2);
    }

    std::cout << polygonSetToWkt(polygon);

    return 0;
}
Esempio n. 2
0
/*----------------------------------------------------------------------
|       TestWhitespace
+---------------------------------------------------------------------*/
static void
TestWhitespace()
{
    const char* xml = 
"<doc>\r\n"
"   <clean>   </clean>\r\n"
"   <dirty>   A   B   </dirty>\r\n"
"   <mixed>\r\n"
"      A\r\n"
"      <clean>   </clean>\r\n"
"      B\r\n"
"      <dirty>   A   B   </dirty>\r\n"
"      C\r\n"
"   </mixed>\r\n"
"</doc>\r\n";

    const char* expect1 = 
"<doc><clean/><dirty>   A   B   </dirty><mixed>\n"
"      A\n"
"      <clean/>\n"
"      B\n"
"      <dirty>   A   B   </dirty>\n"
"      C\n"
"   </mixed></doc>";

    const char* expect2 = 
"<doc>\n"
"   <clean>   </clean>\n"
"   <dirty>   A   B   </dirty>\n"
"   <mixed>\n"
"      A\n"
"      <clean>   </clean>\n"
"      B\n"
"      <dirty>   A   B   </dirty>\n"
"      C\n"
"   </mixed>\n"
"</doc>";

    NPT_XmlParser parser1(false); // ignore whitespace
    NPT_XmlNode* root;
    CHECK(NPT_SUCCEEDED(parser1.Parse(xml, root)));
    CHECK(root);

    NPT_XmlWriter writer;
    NPT_MemoryStream buffer;
    writer.Serialize(*root, buffer);
    CHECK(buffer.GetBuffer() == NPT_DataBuffer(expect1, NPT_StringLength(expect1)));

    delete root;

    NPT_XmlParser parser2(true); // keep whitespace
    CHECK(NPT_SUCCEEDED(parser2.Parse(xml, root)));
    CHECK(root);

    buffer.SetSize(0);
    writer.Serialize(*root, buffer);
    CHECK(buffer.GetBuffer() == NPT_DataBuffer(expect2, NPT_StringLength(expect2)));

    delete root;
}
Esempio n. 3
0
int main() {


  MyExpr::Coll c;
  for (int i=5; i<15; ++i) { c.emplace_back(new Cand(i,1,1)); }
  MyExpr::Res r;

  std::string expr = "void eval(Coll const & c, Res & r) override{ r.resize(c.size()); std::transform(c.begin(),c.end(),r.begin(), [](auto const & c){ return (*c).pt()>10;}); }";

  ExprEval parser("MyExpr",expr.c_str());

  auto func = parser.expr<MyExpr>();

  func->eval(c,r);

  std::cout << r.size()  << ' '  <<  std::count(r.begin(),r.end(),true) << std::endl;


  std::string cut = "bool eval(int i, int j) override { return i<10&& j<5; }";

  ExprEval parser2("vcut",cut.c_str());

  auto mcut = parser2.expr<vcut>();

  std::cout << mcut->eval(2,7) << ' ' << mcut->eval(3, 4) << std::endl;

  return 0;

}
Esempio n. 4
0
/** The main thing.
 * @param argc the number of tokens on the input line.
 * @param argv an array of tokens.
 * @return 0 on success, 1-255 on failure
 */
int main (int argc, char *argv[])
{
  if (argc < 2)
  {
    printf("Usage: mytar [ctxvS]f tarfile [ path [ ... ] ]\n");
    exit(EXIT_FAILURE);
  }

  if (argv[1][0] == '-')
    parser2(argc, argv);
  else
    parser(argv[1]);

  /* Report the final status of the flags */
  if (!f_flag && !help_flag && !version_flag)
  {
    printf("-f option is required\n");
    exit(EXIT_FAILURE);
  }
  else if (help_flag)
    printHelp();
  else if (version_flag)
    printVersion();

  if (!c_flag && !t_flag && !x_flag && !help_flag && !version_flag)
  {
    printf("One operation -c -t or -x is required\n");
    exit(EXIT_FAILURE);
  }

  if ((c_flag && t_flag) || (c_flag && x_flag) || (x_flag && t_flag))
  {
    printf("Only one operation -c -t or -x can be specified\n");
    exit(EXIT_FAILURE);
  }
  
  if (t_flag && f_flag)
  {
    readFile(argv[2]);
  }
  
  if (c_flag)
  {
    printf("Implemented but not properly functioning.\n");
    exit(EXIT_FAILURE);
  }
  if (x_flag)
  {
    printf("Not implemented.\n");
    exit(EXIT_FAILURE);
  }
  
  return EXIT_SUCCESS;
}
Esempio n. 5
0
bool StyleSheetEditorDialog::isStyleSheetValid(const QString &styleSheet)
{
    QCss::Parser parser(styleSheet);
    QCss::StyleSheet sheet;
    if (parser.parse(&sheet))
        return true;
    QString fullSheet = QLatin1String("* { ");
    fullSheet += styleSheet;
    fullSheet += QLatin1Char('}');
    QCss::Parser parser2(fullSheet);
    return parser2.parse(&sheet);
}
Esempio n. 6
0
int main(void)
{
	char input_dir_name0[128];
	char input_dir_name1[128];
	char* num0=new char[3];
	char* num1=new char[3];
	
	cout<<"select number(circuit A): ";
	cin>>num0;
	cout<<"select number(circuit B): ";
	cin>>num1;
	//sprintf(input_dir_name0,"./test file/cadContest2012_ECO_test%s/g1.v",num0);
	sprintf(input_dir_name0, "./testfile/ex%s.v", num0);
	netlist_parser parser1(input_dir_name0);
	Node node1(parser1);
	Wire wire1(parser1);
	BddBuilder * bddBuilder0 = new BddBuilder();
	bddBuilder0->construct(wire1.list(), node1.list());
	bddBuilder0->dotDump();
	VerilogMaker* Maker=new VerilogMaker(node1.list(),"g1");
	Maker->Function();
	sprintf(input_dir_name1, "./testfile/ex%s.v", num1);
	netlist_parser parser2(input_dir_name1);
	Node node2(parser2);
	Wire wire2(parser2);
	BddBuilder * bddBuilder1 = new BddBuilder(bddBuilder0);
	bddBuilder1->constructB(bddBuilder0, wire2.list(), node2.list());
	bddBuilder1->dotDump();

	DdNode ** xordlist = bddBuilder0->getXORdNodeList(bddBuilder1);
	bddBuilder0->dotDumpC(xordlist);

	DdNode ** xordA = bddBuilder0->getXORdNodeList(xordlist);	
	//bddBuilder0->dotDumpC(xordA);
	
	if(bddBuilder1->checkEquality(xordA) == 0)
		printf("Equality check succeed.\n");



	delete Maker;
	delete []xordA;
	delete []xordlist;
	delete bddBuilder0;
	delete bddBuilder1;
	delete []num0;
	delete []num1;
	return 0;
}
Esempio n. 7
0
    bool Version::operator < (Version ver) {
        //Version string could have a wide variety of formats. Use regex to choose specific comparison types.

        regex reg1("(\\d+\\.?)+");  //a.b.c.d.e.f.... where the letters are all integers, and 'a' is the shortest possible match.

        //boost::regex reg2("(\\d+\\.?)+([a-zA-Z\\-]+(\\d+\\.?)*)+");  //Matches a mix of letters and numbers - from "0.99.xx", "1.35Alpha2", "0.9.9MB8b1", "10.52EV-D", "1.62EV" to "10.0EV-D1.62EV".

        if (regex_match(verString, reg1) && regex_match(ver.AsString(), reg1)) {
            //First type: numbers separated by periods. If two versions have a different number of numbers, then the shorter should be padded
            //with zeros. An arbitrary number of numbers should be supported.
            istringstream parser1(verString);
            istringstream parser2(ver.AsString());
            while (parser1.good() || parser2.good()) {
                //Check if each stringstream is OK for i/o before doing anything with it. If not, replace its extracted value with a 0.
                uint32_t n1, n2;
                if (parser1.good()) {
                    parser1 >> n1;
                    parser1.get();
                } else
Esempio n. 8
0
int main()
{
	ANTLR_USING_NAMESPACE(std);
	ANTLR_USING_NAMESPACE(antlr);
	try
	{
		SimpleLexer lexer(cin);

		/* Invoke first parser */
		cout << "first parser" << endl;
		SimpleParser parser(lexer);
		parser.simple();

		/* Now we need to get the inputState from the first parser
		 * this includes data about guessing and stuff like it.
		 * If we don't do this and create the second parser
		 * with just the lexer object we might (doh! will!) miss tokens
		 * read for lookahead tests.
		 */
		ParserSharedInputState inputstate(parser.getInputState());

		/* When first parser runs out, invoke secnond parser */
		cout << "second parser" << endl;
		SimpleParser2 parser2(inputstate);
		parser2.simple();
	}
	catch( ANTLRException& e )
	{
		cerr << "exception: " << e.getMessage() << endl;
		return -1;
	}
	catch( exception& e )
	{
		cerr << "exception: " << e.what() << endl;
		return -1;
	}
	return 0;
}
Esempio n. 9
0
PVideoFrame __stdcall ConditionalFilter::GetFrame(int n, IScriptEnvironment* env) {

  VideoInfo vi1 = source1->GetVideoInfo();
  VideoInfo vi2 = source2->GetVideoInfo();

  AVSValue prev_last = env->GetVar("last");  // Store previous last
  AVSValue prev_current_frame = GetVar(env, "current_frame");  // Store previous current_frame

  env->SetVar("last",(AVSValue)child);       // Set implicit last
  env->SetVar("current_frame",(AVSValue)n);  // Set frame to be tested by the conditional filters.

  AVSValue e1_result;
  AVSValue e2_result;
  try {
    ScriptParser parser(env, eval1.AsString(), "[Conditional Filter, Expresion 1]");
    PExpression exp = parser.Parse();
    e1_result = exp->Evaluate(env);

    ScriptParser parser2(env, eval2.AsString(), "[Conditional Filter, Expression 2]");
    exp = parser2.Parse();
    e2_result = exp->Evaluate(env);
  } catch (AvisynthError error) {    
    const char* error_msg = error.msg;  

    PVideoFrame dst = source1->GetFrame(n,env);
    env->MakeWritable(&dst);
    ApplyMessage(&dst, vi1, error_msg, vi.width/W_DIVISOR, 0xa0a0a0,0,0 , env );
    env->SetVar("last",prev_last);       // Restore implicit last
    env->SetVar("current_frame",prev_current_frame);       // Restore current_frame
    return dst;
  }

  env->SetVar("last",prev_last);       // Restore implicit last
  env->SetVar("current_frame",prev_current_frame);       // Restore current_frame

  int test_int=false;

  int e1 = 0;
  int e2 = 0;
  float f1 = 0.0f;
  float f2 = 0.0f;
  try {
    if (e1_result.IsInt() || e1_result.IsBool()) {
      test_int = true;
      e1 = e1_result.IsInt() ? e1_result.AsInt() : e1_result.AsBool();
      if (!(e2_result.IsInt() || e2_result.IsBool()))
        env->ThrowError("Conditional filter: Second expression did not return an integer or bool, as first expression.");
      e2 = e2_result.IsInt() ? e2_result.AsInt() : e2_result.AsBool();

    } else if (e1_result.IsFloat()) {
      f1 = e1_result.AsFloat();
      if (!e2_result.IsFloat()) 
        env->ThrowError("Conditional filter: Second expression did not return a float or an integer, as first expression.");
      f2 = e2_result.AsFloat();
    } else {
      env->ThrowError("ConditionalFilter: First condition did not return an int, bool or float!");
    }
  } catch (AvisynthError error) {    
    const char* error_msg = error.msg;  

    PVideoFrame dst = source1->GetFrame(n,env);
    env->MakeWritable(&dst);
    ApplyMessage(&dst, vi1, error_msg, vi.width/W_DIVISOR, 0xa0a0a0,0,0 , env );
    return dst;
  }


  bool state = false;

  if (test_int) {
    if (evaluator&EQUALS) 
      if (e1 == e2) state = true;

    if (evaluator&GREATERTHAN) 
      if (e1 > e2) state = true;

    if (evaluator&LESSTHAN) 
      if (e1 < e2) state = true;
  } else {  // Float compare
    if (evaluator&EQUALS) 
      if (fabs(f1-f2)<0.000001f) state = true;   // Exact equal will sometimes be rounded to wrong values.

    if (evaluator&GREATERTHAN) 
      if (f1 > f2) state = true;

    if (evaluator&LESSTHAN) 
      if (f1 < f2) state = true;    
  }

  if (show) {
      char text[400];
      if (test_int) {
        sprintf(text,
          "Left side Conditional Result:%i\n"
          "Right side Conditional Result:%i\n"
          "Evaluate result: %s\n",
          e1, e2, (state) ? t_TRUE : t_FALSE
        );
      } else {
        sprintf(text,
          "Left side Conditional Result:%7.4f\n"
          "Right side Conditional Result:%7.4f\n"
          "Evaluate result: %s\n", 
          f1, f2, (state) ? t_TRUE : t_FALSE
        );
      }

      PVideoFrame dst = (state) ? source1->GetFrame(min(vi1.num_frames-1,n),env) : source2->GetFrame(min(vi2.num_frames-1,n),env);
      env->MakeWritable(&dst);
      ApplyMessage(&dst, vi, text, vi.width/4, 0xa0a0a0,0,0 , env );

    return dst;
  }

  if (state) 
    return source1->GetFrame(min(vi1.num_frames-1,n),env);
  
  return source2->GetFrame(min(vi1.num_frames-1,n),env);
}
Esempio n. 10
0
bool
ClParserParser::
parse()
{
  ClParserOperatorType op = CL_PARSER_OP_NONE;

  error_code_ = 0;

  bool expression = false;

  parse_.skipSpace();

  while (! parse_.eof()) {
    /* <expression> := <inline_operator> <expression>
       <expression> := <expression> <inline_operator> */

    if      (parse_.isString("++") || parse_.isString("--")) {
      if (parse_.isChar('+'))
        ClParserStackMgrInst->push(CL_PARSER_OP_INCREMENT);
      else
        ClParserStackMgrInst->push(CL_PARSER_OP_DECREMENT);

      ClParserStackMgrInst->toNext();

      parse_.skipChars(2);

      if (! expression) {
        ClParserParser parser(this);

        if (! parser.parse()) {
          error_code_ = parser.getErrorCode();
          goto fail;
        }

        if (parser.isAssign()) {
          error_code_ = int(ClErr::INVALID_LVALUE_FOR_ASSIGNMENT);
          goto fail;
        }
      }

      expression = true;
    }

    /* <expression> := <unary_operator> <expression> */

    else if (! expression && parse_.isOneOf(parser_unary_operator_chars)) {
      if (! readUnaryOperator(&op)) {
        error_code_ = int(ClErr::INVALID_CHARACTER);
        goto fail;
      }

      ClParserStackMgrInst->push(op);

      ClParserStackMgrInst->toNext();

      ClParserParser parser(this);

      if (! parser.parse()) {
        error_code_ = parser.getErrorCode();
        goto fail;
      }

      if (parser.isAssign()) {
        error_code_ = int(ClErr::INVALID_LVALUE_FOR_ASSIGNMENT);
        goto fail;
      }

      expression = true;
    }

    /* <expression> := '(' <expression> ')' */

    else if (! expression && parse_.isChar('(')) {
      ClParserStackMgrInst->push(CL_PARSER_OP_OPEN_R_BRACKET);

      ClParserStackMgrInst->toNext();

      parse_.skipChar();

      ClParserParser parser(this);

      /* TODO: set end char */
      if (! parser.parse() &&
          parser.getErrorCode() != int(ClErr::INVALID_CHARACTER)) {
        error_code_ = parser.getErrorCode();
        goto fail;
      }

      parse_.skipSpace();

      if (! parse_.isChar(')')) {
        error_code_ = int(ClErr::MISSING_CLOSE_ROUND_BRACKET);
        goto fail;
      }

      ClParserStackMgrInst->push(CL_PARSER_OP_CLOSE_R_BRACKET);

      ClParserStackMgrInst->toNext();

      parse_.skipChar();

      expression = true;
    }

    /* <expression> := <numeric_value> */

    else if (! expression && (parse_.isDigit() || parse_.isChar('.'))) {
      ClParserValuePtr value;

      if (! readNumericValue(value))
        goto fail;

      ClParserStackMgrInst->push(value);

      ClParserStackMgrInst->toNext();

      expression = true;
    }

    /* <expression> := <string_value> */

    else if (! expression && parse_.isOneOf(parser_string_chars)) {
      ClParserValuePtr value;

      if (! readStringValue(value))
        goto fail;

      ClParserStackMgrInst->push(value);

      ClParserStackMgrInst->toNext();

      expression = true;
    }

    /* <expression> := <array_value> */

    else if (! expression && parse_.isChar('[')) {
      ClParserStackMgrInst->push(CL_PARSER_OP_OPEN_S_BRACKET);

      ClParserStackMgrInst->toNext();

      parse_.skipChar();

      if (! readArray())
        goto fail;

      expression = true;
    }

    /* <expression> := <dict_value> */

    else if (! expression && parse_.isString("{{")) {
      ClParserStackMgrInst->push(CL_PARSER_OP_OPEN_DICT);

      ClParserStackMgrInst->toNext();

      parse_.skipChars(2);

      if (! readDictionary())
        goto fail;

      expression = true;
    }

    /* <expression> := <list_value> */

    else if (! expression && parse_.isChar('{')) {
      ClParserStackMgrInst->push(CL_PARSER_OP_OPEN_BRACE);

      ClParserStackMgrInst->toNext();

      parse_.skipChar();

      if (! readList())
        goto fail;

      expression = true;
    }

    /* <expression> := <expression> <binary_operator> <expression> */

    else if (expression && parse_.isOneOf(parser_binary_operator_chars)) {
      if (! readBinaryOperator(&op))
        goto fail;

      ClParserStackMgrInst->push(op);

      ClParserStackMgrInst->toNext();

      ClParserParser parser(this);

      if (! parser.parse()) {
        error_code_ = parser.getErrorCode();
        goto fail;
      }

      ClParserOperatorPtr op1 = ClParserOperatorMgrInst->getOperator(op);

      if (! op1->isAssignment() && parser.isAssign()) {
        error_code_ = int(ClErr::INVALID_LVALUE_FOR_ASSIGNMENT);
        goto fail;
      }

      if (op1->isAssignment())
        assign_ = true;

      expression = true;
    }

    /* <expression> := <expression> '?' <expression> ':' <expression> */

    else if (expression && parse_.isChar('?')) {
      ClParserStackMgrInst->push(CL_PARSER_OP_QUESTION_MARK);

      ClParserStackMgrInst->toNext();

      parse_.skipChar();

      ClParserParser parser1(this);

      if (! parser1.parse() &&
          parser1.getErrorCode() != int(ClErr::INVALID_CHARACTER)) {
        error_code_ = parser1.getErrorCode();
        goto fail;
      }

      parse_.skipSpace();

      if (! parse_.isChar(':')) {
        error_code_ = int(ClErr::MISSING_COLON_OPERATOR);
        goto fail;
      }

      ClParserStackMgrInst->push(CL_PARSER_OP_COLON);

      ClParserStackMgrInst->toNext();

      parse_.skipChar();

      ClParserParser parser2(this);

      if (! parser2.parse() &&
          parser2.getErrorCode() != int(ClErr::INVALID_CHARACTER)) {
        error_code_ = parser2.getErrorCode();
        goto fail;
      }

      assign_ = parser1.isAssign() | parser2.isAssign();

      expression = true;
    }

    /* <expression> := <expression> '[' <expression> ',' .... ']' */

    else if (expression && parse_.isChar('[')) {
      ClParserStackMgrInst->push(CL_PARSER_OP_OPEN_S_BRACKET);

      ClParserStackMgrInst->toNext();

      parse_.skipChar();

      if (! readArray())
        goto fail;

      expression = true;
    }

    /* <expression> := <expression> ',' <expression> */

    else if (expression && parse_.isChar(',')) {
      ClParserStackMgrInst->push(CL_PARSER_OP_COMMA);

      ClParserStackMgrInst->toNext();

      parse_.skipChar();

      ClParserParser parser(this);

      if (! parser.parse()) {
        error_code_ = parser.getErrorCode();
        goto fail;
      }

      expression = true;
    }

    /* <expression> := <variable>                               */
    /* <expression> := <variable> '.' <variable> '.' <...>      */
    /* <expression> := <variable> '[' <expression> ',' .... ']' */
    /* <expression> := <function> '(' <expression> ',' .... ')' */
    /* <expression> := <type>     '(' <expression> ',' .... ')' */

    else if (! expression &&
             ((! ClParserInst->getDollarPrefix() && parse_.isIdentifier()) ||
              (  ClParserInst->getDollarPrefix() &&
               parse_.isChar('$') && parse_.isIdentifier(1)))) {
      if (ClParserInst->getDollarPrefix() && parse_.isChar('$'))
        parse_.skipChar();

      ClParserIdentifierPtr identifier;

      if (! readIdentifier(identifier))
        goto fail;

      const std::string &name  = identifier->getName();
      ClParserScopePtr   scope = identifier->getScope();

      parse_.skipSpace();

      if (parse_.isChar('(')) {
        ClParserInternFnPtr internfn;

        if (scope.isValid())
          internfn = scope->getInternFn(name);
        else
          internfn = ClParserInst->getInternFn(name);

        if (internfn.isValid()) {
          ClParserStackMgrInst->push(internfn);

          ClParserStackMgrInst->toNext();
        }
        else {
          ClParserUserFnPtr userfn;

          if (scope.isValid())
            userfn = scope->getUserFn(name);
          else
            userfn = ClParserInst->getUserFn(name);

          if (userfn.isValid()) {
            ClParserStackMgrInst->push(userfn);

            ClParserStackMgrInst->toNext();
          }
          else {
            ClParserTypePtr type = ClParserInst->getType(name);

            if (type.isValid()) {
              ClParserStackMgrInst->push(type);

              ClParserStackMgrInst->toNext();
            }
            else {
              identifier->setFunction();

              ClParserStackMgrInst->push(identifier);

              ClParserStackMgrInst->toNext();
            }
          }
        }

        ClParserStackMgrInst->push(CL_PARSER_OP_OPEN_R_BRACKET);

        ClParserStackMgrInst->toNext();

        parse_.skipChar();

        if (! readArgList())
          goto fail;

        expression = true;
      }
      else {
        identifier->setVariable();

        ClParserStackMgrInst->push(identifier);

        ClParserStackMgrInst->toNext();

        if (parse_.isChar('[')) {
          ClParserStackMgrInst->push(CL_PARSER_OP_OPEN_S_BRACKET);

          ClParserStackMgrInst->toNext();

          parse_.skipChar();

          if (! readArray())
            goto fail;

          parse_.skipSpace();
        }

        while (parse_.isChar('.')) {
          identifier->setStructPart();

          ClParserStackMgrInst->push(CL_PARSER_OP_DOT);

          ClParserStackMgrInst->toNext();

          parse_.skipChar();

          parse_.skipSpace();

          if (! readIdentifier(identifier)) {
            error_code_ = int(ClErr::INVALID_CHARACTER);
            goto fail;
          }

          identifier->setVariable();

          ClParserStackMgrInst->push(identifier);

          ClParserStackMgrInst->toNext();

          if (parse_.isChar('[')) {
            ClParserStackMgrInst->push(CL_PARSER_OP_OPEN_S_BRACKET);

            ClParserStackMgrInst->toNext();

            parse_.skipChar();

            if (! readArray())
              goto fail;

            parse_.skipSpace();
          }
        }

        expression = true;
      }
    }
    /* <expression> := <string_value> */

    else if (! expression && ClParserInst->getDollarPrefix()) {
      std::string str;

      parse_.readNonSpace(str);

      ClParserValuePtr value = ClParserValueMgrInst->createValue(str);

      ClParserStackMgrInst->push(value);

      ClParserStackMgrInst->toNext();

      parse_.skipSpace();

      expression = true;
    }
    else {
      error_code_ = int(ClErr::INVALID_CHARACTER);
      goto fail;
    }

    parse_.skipSpace();
  }

  if (error_code_ == 0 && ! expression) {
    error_code_ = int(ClErr::NULL_EXPRESSION);
    goto fail;
  }

  if (parent_)
    parent_->parse_.setPos(parent_->parse_.getPos() + parse_.getPos());

  return true;

 fail:
  if (parent_)
    parent_->parse_.setPos(parent_->parse_.getPos() + parse_.getPos());

  return false;
}
void UT_command_line_parser(const char* params)
{
	char tmp[100];
	Lumix::CommandLineParser parser("-x 10 -y 20\t-plugin  custom.dll -str \"test\" -str2 \"test with spaces\"");

	LUMIX_EXPECT_TRUE(parser.next());
	LUMIX_EXPECT_TRUE(parser.currentEquals("-x"));
	LUMIX_EXPECT_FALSE(parser.currentEquals("-y"));
	LUMIX_EXPECT_FALSE(parser.currentEquals("-"));
	LUMIX_EXPECT_FALSE(parser.currentEquals(""));
	LUMIX_EXPECT_FALSE(parser.currentEquals("10"));

	LUMIX_EXPECT_TRUE(parser.next());
	LUMIX_EXPECT_TRUE(parser.currentEquals("10"));

	LUMIX_EXPECT_TRUE(parser.next());
	LUMIX_EXPECT_TRUE(parser.currentEquals("-y"));

	LUMIX_EXPECT_TRUE(parser.next());
	LUMIX_EXPECT_TRUE(parser.currentEquals("20"));

	LUMIX_EXPECT_TRUE(parser.next());
	LUMIX_EXPECT_TRUE(parser.currentEquals("-plugin"));

	LUMIX_EXPECT_TRUE(parser.next());
	LUMIX_EXPECT_TRUE(parser.currentEquals("custom.dll"));
	parser.getCurrent(tmp, Lumix::lengthOf(tmp));
	LUMIX_EXPECT_TRUE(Lumix::compareString(tmp, "custom.dll") == 0);

	LUMIX_EXPECT_TRUE(parser.next());
	LUMIX_EXPECT_TRUE(parser.currentEquals("-str"));

	LUMIX_EXPECT_TRUE(parser.next());
	LUMIX_EXPECT_TRUE(parser.currentEquals("\"test\""));
	parser.getCurrent(tmp, Lumix::lengthOf(tmp));
	LUMIX_EXPECT_TRUE(Lumix::compareString(tmp, "\"test\"") == 0);

	LUMIX_EXPECT_TRUE(parser.next());
	LUMIX_EXPECT_TRUE(parser.currentEquals("-str2"));

	LUMIX_EXPECT_TRUE(parser.next());
	LUMIX_EXPECT_TRUE(parser.currentEquals("\"test with spaces\""));
	parser.getCurrent(tmp, Lumix::lengthOf(tmp));
	LUMIX_EXPECT_TRUE(Lumix::compareString(tmp, "\"test with spaces\"") == 0);


	LUMIX_EXPECT_FALSE(parser.next());

	Lumix::CommandLineParser parser2("");
	LUMIX_EXPECT_FALSE(parser2.next());

	Lumix::CommandLineParser parser3("  ");
	LUMIX_EXPECT_FALSE(parser3.next());

	Lumix::CommandLineParser parser4("\t");
	LUMIX_EXPECT_FALSE(parser4.next());

	Lumix::CommandLineParser parser5("\"\"");
	LUMIX_EXPECT_TRUE(parser5.next());
	LUMIX_EXPECT_TRUE(parser5.currentEquals("\"\""));
	LUMIX_EXPECT_FALSE(parser5.next());

	Lumix::CommandLineParser parser6(" \" \" ");
	LUMIX_EXPECT_TRUE(parser6.next());
	parser6.getCurrent(tmp, Lumix::lengthOf(tmp));
	LUMIX_EXPECT_TRUE(Lumix::compareString(tmp, "\" \"") == 0);
	LUMIX_EXPECT_TRUE(parser6.currentEquals("\" \""));
	LUMIX_EXPECT_FALSE(parser6.next());
}
Esempio n. 12
0
bool CKReader::read(const std::string& inputFile, const std::string& thermoDatabase, 
		    const std::string& logfile) {

    clock_t t0, t1;

    t0 = clock();

    ifstream ckinfile(inputFile.c_str());
    ofstream log(logfile.c_str());
    try {
    // construct a parser for the input file
    CKParser parser(&ckinfile, inputFile, &log);
    parser.verbose = verbose;
    parser.debug = debug;

    // write header information to the log file
    struct tm *newtime;
    time_t aclock;
    time( &aclock );                  /* Get time in seconds */
    newtime = localtime( &aclock );   /* Convert time to struct tm form */

    
    log << "CKReader version 1.0" << endl
        << "http://www.cantera.org" << endl << endl
        << asctime(newtime) << endl
        << setw(20) << "input file: " 
        << setw(30) << inputFile << endl;
    
    if (thermoDatabase != "") 
        log << setw(20) << "species database: " 
            << setw(30) << thermoDatabase << endl;
    
    if (!validate) 
        log << endl << "***************  Warning  ***************" << endl
            <<         "     mechanism validation disabled"        << endl
            <<         "*****************************************" << endl;

    if (debug) {
        log << "*** DEBUG MODE ***" << endl;
    }
    else {
        log << "debugging disabled." << endl;
    }

    //-----------   process ELEMENT section  ----------------------

    bool elok = parser.readElementSection(elements);
    int nel = static_cast<int>(elements.size());
    vector<string> elementSymbols;
    for (int j = 0; j < nel; j++) elementSymbols.push_back(elements[j].name);

    if (verbose) {
        log.flags(ios::showpoint);
        log.precision(6);
        log.width(0);

        log << endl << newTask("reading elements") << endl;
    
        // write summary to log file
        for (int i = 0; i < nel; i++) {
            log << i+1 << ".  " << pad(elements[i].name,2) << "  ";
            double wt = elements[i].atomicWeight;
            if (wt == 0.0) log << "<error>";
            else log << wt;
            if (!elements[i].weightFromDB) log << " (specified)";
            if (elements[i].comment != "") 
                log << "      ! " << elements[i].comment;
            log << endl;
        }
    }
    log << "\nread " << nel << " elements." << endl;
    
    if (!elok) {
        log << "\nerrors were encountered." << endl;
        return false;
    }
    if (nel == 0) {
        return false;
    }


    //------------   process SPECIES section  ------------------------

    vector<string> speciesSymbols;
    bool spok = parser.readSpeciesSection(species);
    int nsp = static_cast<int>(species.size());

    if (verbose) log << newTask("reading species") << endl;

    for (int i = 0; i < nsp; i++) {
        Species& s = species[i];
        if (verbose) log << i+1 << ".  " << s.name << endl;
        speciesSymbols.push_back(s.name);
    }
    log << "\nread " << nsp << " species." << endl;

    if (!spok) {
        log << "\nerrors were encountered." << endl;
        return false;
    }
    if (nsp == 0) return false;


    //-------------   process THERMO section  -------------------------

    if (verbose) log << newTask("looking up species definitions") << endl;

    // if a thermo database is specified, get the default Tmin, Tmid, Tmax
    vector_fp temp;

    if (thermoDatabase != "") {

        if (verbose) log << "reading default temperature ranges from " 
                         << thermoDatabase  << endl;

        ifstream thermofile(thermoDatabase.c_str());
        CKParser thermReader(&thermofile, thermoDatabase, &log);
        thermReader.verbose = verbose;
        thermReader.debug = debug;
        int dbflag = HasTempRange;
        vector<string> dummy;
        thermReader.readThermoSection(dummy, speciesData, temp, dbflag, log);
    }

    
    bool hasthermo = parser.advanceToKeyword("THERM","REAC");

    int k, optionFlag = 0;
    int undefined = static_cast<int>(species.size());
    string nm;
    vector<string> undef;
    bool allsp = (speciesSymbols[0] == "<ALL>");
    if (hasthermo && 
	parser.readThermoSection(speciesSymbols,
				 speciesData, temp, optionFlag, log)) {
        if (allsp) {
            nsp = static_cast<int>(speciesData.size()); 
            for (k = 0; k < nsp; k++) {
                Species s;
                s.name = speciesSymbols[k];
                species.push_back(s);
            }
        }
        undefined = 0;
        for (k = 0; k < nsp; k++) {
            nm = species[k].name;
            species[k] = speciesData[species[k].name];
            if (species[k].name == "<empty>") {
                undefined++;
                undef.push_back(nm);
                species[k].name = nm;
            }
        }
        int localdefs = nsp - undefined;
        if (localdefs > 0 && verbose) log << "found definitions for " 
                                          << localdefs 
                                          << " of " 
                                          << nsp 
                                          << " species in the input file. " 
                                          << endl;
    }
    else {
        undef = speciesSymbols;
        if (verbose) log << "no THERMO section in input file." << endl;
    }

    if (undefined > 0 && thermoDatabase != "" 
        && optionFlag != NoThermoDatabase) {

        if (verbose) log << "searching external database " 
                         << thermoDatabase << " for species definitions..."
                         << endl;

        ifstream thermofile(thermoDatabase.c_str());
        CKParser thermoReader(&thermofile, thermoDatabase, &log);
        thermoReader.verbose = verbose;
        thermoReader.debug = debug;
        int dbflag = HasTempRange;
        thermoReader.readThermoSection(undef, speciesData, temp, dbflag, log);
        undefined = 0;
        if (allsp) {
            species.clear();
            nsp = static_cast<int>(speciesData.size()); 
            for (k = 0; k < nsp; k++) {
                Species s;
                s.name = undef[k];
                species.push_back(s);
            }
        }
        for (int k = 0; k < nsp; k++) {
            if (species[k].valid == 0) {
                nm = species[k].name;
                species[k] = speciesData[species[k].name];
                if (species[k].name == "<empty>") {
                    undefined++;
                    species[k].name = nm;
                }
            }
        }
    }

    if (validate && !validateSpecies(log)) {
      //Cantera::setError("read","error in species");
        return false;
    }


    //-------------   process REACTIONS section  -------------------------

    if (verbose) log << newTask("reading reactions") << endl;

    ckinfile.close();
    ifstream ckinfile2(inputFile.c_str());

    // construct a new parser for the input file
    CKParser parser2(&ckinfile2, inputFile, &log);
    parser2.verbose = verbose;
    parser2.debug = debug;

    parser2.readReactionSection(speciesSymbols, elementSymbols, reactions, units);
    log << "\nread " << static_cast<int>(reactions.size()) 
		<< " reactions." << endl;

    bool rxnok = true;
    if (validate) rxnok = rxnok && validateReactions(log);
    bool writeok = true;
    if (verbose || validate)  writeok = writeReactions(log);
    rxnok = rxnok && writeok;
    if (!rxnok) return false;

    log << "\nSuccess... ";
    t1 = clock();
    log << "elapsed CPU time = " 
        << double(t1 - t0)/CLOCKS_PER_SEC 
        << " s" << endl;
    if (!validate) log << "*** no validation performed ***" << endl;
    }

    catch (CK_Exception e) {
        log << e.errorMessage() << endl;
        //Cantera::setError("CKReader::read",e.errorMessage());
        return false;
    }
    catch (...) {
        log << "an exception was raised in CKReader.";
        return false;
    }

    return true;
}