Exemplo n.º 1
0
///////////////////////////////////////////////////////////////////////////////
//  Main program
///////////////////////////////////////////////////////////////////////////////
void parseDXtoD(std::string const &path)
{
	typedef std::string::const_iterator iterator_type;
	typedef DiasEx::gram<iterator_type> grammar;

	namespace qi = boost::spirit::qi;

	grammar gram; // Our grammar

	auto &file = bfe::File{path}.bytes;
	auto str = std::string{file.begin(), file.end()};
	auto iter = str.begin();
	auto end = str.end();
	auto ast = AST::nspace{""};

	bool r = phrase_parse(iter, end, gram, boost::spirit::ascii::space, ast);

	if(r && iter == end) {
		std::cout << "parsing succeeded. See output file.\n";
		auto output = ast.transform();
		bfe::File::write("output.txt", {output.begin(), output.end()});
	}
	else {
		std::cout << "parsing failed at: " + std::string{iter, end} + "\n";
	}
}
Exemplo n.º 2
0
/**
 * 指定された変数を、数値に変換する。
 *
 * @param attr_name		変数名
 * @param shape			shape
 * @return				変換された数値
 */
float RuleSet::evalFloat(const std::string& attr_name, const boost::shared_ptr<Shape>& shape) const {
	myeval::calculator<std::string::const_iterator> calc;

	myeval::variables.clear();
	myeval::variables.add("scope.sx", shape->_scope.x);
	myeval::variables.add("scope.sy", shape->_scope.y);
	myeval::variables.add("scope.sz", shape->_scope.z);

	for (auto it = attrs.begin(); it != attrs.end(); ++it) {
		float val;
		if (sscanf(it->second.c_str(), "%f", &val) != EOF) {
			myeval::variables.add(it->first, val);
		}
	}

	float result;
	std::string::const_iterator iter = attr_name.begin();
	std::string::const_iterator end = attr_name.end();
	bool r = phrase_parse(iter, end, calc, boost::spirit::ascii::space, result);
	if (r && iter == end) {
		return result;
	} else {
		std::string rest(iter, end);
		std::cout << "Parsing failed\n";
		std::cout << "stopped at: \": " << rest << "\"\n";
		throw "Parsing failed\nstpped at: \": " + rest + "\"\n";
	}
}
Exemplo n.º 3
0
int main(int argc, char* argv[])
{
    std::string test="123";
    std::string test_vector="456 789";

    qi::rule<std::string::const_iterator,std::string()> my_int_as_str = qi::attr_cast(qi::int_);
    qi::rule<std::string::const_iterator,std::vector<std::string>(),qi::space_type> my_int_as_str_vector= *qi::attr_cast(qi::int_);

    std::string result;
    std::vector<std::string> result_vector;

    parse(test.cbegin(),test.cend(),my_int_as_str,result);
    phrase_parse(test_vector.cbegin(),test_vector.cend(),my_int_as_str_vector,qi::space,result_vector);


    std::cout << result << std::endl;
    for(auto& string: result_vector)
        std::cout << string << std::endl;

std::string string_semantic;
qi::parse(test.cbegin(),test.cend(),qi::int_[&semantic_transform],string_semantic);
std::cout << string_semantic << std::endl;

    return 0;
}
Exemplo n.º 4
0
    path_list_t parse(std::string const& s) 
    {
	path_list_t paths;
	string_iter_t first = s.begin();
        if (!phrase_parse(first, s.end(), path_parser, boost::spirit::ascii::space, paths) || first != s.end()) {
	    throw std::invalid_argument(std::string("Parsing error: unexpected \"") + std::string(first, s.end()) + std::string("\""));
	}
	return paths;
    }
Exemplo n.º 5
0
 inline bool
 phrase_parse(
     Iterator& first
   , Iterator last
   , Parser const& p
   , Skipper const& s
   , skip_flag post_skip = skip_flag::post_skip)
 {
     return phrase_parse(first, last, p, s, unused, post_skip);
 }
Exemplo n.º 6
0
int main() {
  std::string s;
  std::getline(std::cin, s);
  Iterator beg = s.begin(), end = s.end();
 std:string ret;
  phrase_parse(beg, end, WikiWordParser(), ascii::space, ret);
  if (beg != end)
    puts("Parse failed.");
  else
    std::cout << "WikiWord is '" << ret << "'" << std::endl; 
}
Exemplo n.º 7
0
std::list<Rule*>LexicalAnalyzer::analyze(std::string input)
{
	namespace qi = boost::spirit::qi;
	ItRulesGrammar grammar;
	std::list<Rule*> rules;
	std::string::const_iterator iter = input.begin();
	std::string::const_iterator end = input.end();

	phrase_parse(iter, end, grammar, qi::ascii::blank, rules);
	set_rule_token_previous(rules);
	return rules;
}
Exemplo n.º 8
0
int main(int argc, char **argv) {
    char const* filename;
    if (argc > 1) {
        filename = argv[1];
    } else {
        std::cerr << "Error: No input file provided." << std::endl;
        return 1;
    }

    std::ifstream in(filename, std::ios_base::in);

    if (!in) {
        std::cerr << "Error: Could not open input file: "
            << filename << std::endl;
        return 1;
    }

    std::string storage; // We will read the contents here.
    in.unsetf(std::ios::skipws); // No white space skipping!
    std::copy(
        std::istream_iterator<char>(in),
        std::istream_iterator<char>(),
        std::back_inserter(storage));

    cga::cga_grammar<std::string::const_iterator> g;
    cga::CGARules cga_rules; // Our tree

    std::string::const_iterator iter = storage.begin();
    std::string::const_iterator end = storage.end();

	/// EmployeeParserと同様、3番目の引数がgrammarだ。つまり、mini_xml_grammarを使ってparseする。
	// 4番目の引数はskipする文字。つまり、空白をskipする
	// 5番目の引数に結果が返却される。
    bool r = phrase_parse(iter, end, g, boost::spirit::ascii::space, cga_rules);

    if (r && iter == end) {
        std::cout << "-------------------------\n";
        std::cout << "Parsing succeeded\n";
        std::cout << "-------------------------\n";
		for (auto it = cga_rules.begin(); it != cga_rules.end(); ++it) {
			std::cout << it->first << " --> " << it->second->to_string() << std::endl;
		}
        return 0;
    } else {
        std::string::const_iterator some = iter+30;
        std::string context(iter, (some>end)?end:some);
        std::cout << "-------------------------\n";
        std::cout << "Parsing failed\n";
        std::cout << "stopped at: \": " << context << "...\"\n";
        std::cout << "-------------------------\n";
        return 1;
    }
}
Exemplo n.º 9
0
void RuleInputParser::read_rulefile(const std::string& filename, 
				    std::vector<Rule>& lexicals,
				    std::vector<Rule>& unaries,
				    std::vector<Rule>& n_aries
				    ) throw(ParseError)
{
  
  std::ifstream in_file(filename.c_str(),std::ios::in);
  
  if (!in_file)
  {
    std::cerr << "can't open file: " + filename  << std::endl;
    exit(1);
  }

  std::string str;

  in_file.unsetf(std::ios::skipws); // No white space skipping!
  std::copy(
	    std::istream_iterator<char>(in_file),
	    std::istream_iterator<char>(),
	    std::back_inserter(str));
  

  std::string::const_iterator iter = str.begin();
  std::string::const_iterator end = str.end();
  
  typedef std::string::const_iterator iterator_type;
  typedef rule_parser<iterator_type> parser;
  
  parser p;
  
  bool res;
  do {
    Rule r;
    res = phrase_parse(iter, end, p, mychar::space, r);

    if(!res) {
      // std::cout << "not read: " << std::string(iter,end) << std::endl;
      throw(ParseError(filename));
    }

    if(r.is_lexical()) 
      lexicals.push_back(r);
    else
      if(r.is_unary()) 
	unaries.push_back(r);
      else 
	n_aries.push_back(r);
  } while(res && iter != end);
  
  in_file.close();
}
Exemplo n.º 10
0
Arquivo: main.cpp Projeto: CCJY/coliru
int main()
{
    ConditionTree oTree;

    Parser<> parser(oTree);

    std::string strTest("limit5minutes");

    std::string::const_iterator it_begin(strTest.begin());
    std::string::const_iterator it_end(strTest.end());

    bool result = phrase_parse(it_begin, it_end, parser, ascii::space);
}
Exemplo n.º 11
0
      electrumwallet( std::string path ):encryption(false),seed_version(""),masterkey("")
      {
         std::ifstream in(path, std::ios_base::in);
         std::string storage;
         in.unsetf( std::ios::skipws );
         std::copy( std::istream_iterator<char>(in),
                    std::istream_iterator<char>(),
                    std::back_inserter(storage) );

         bts::parser<std::string::const_iterator> grammar;
         bts::python_dict_type_t dict;

         std::string::const_iterator iter = storage.begin();
         std::string::const_iterator end = storage.end();
         bool r = phrase_parse( iter, end, grammar, ascii::space, dict );

         if( r && iter == end )
         {
            for( auto &item : dict.items )
            {
               boost::to_lower( item.first );
               if( item.first == "use_encryption" )
               {
                  auto useenc = boost::get<std::string>( item.second );
                  boost::to_lower(useenc);
                  if ( useenc == "true" )
                     encryption = true;
               }
               else if( item.first == "seed_version" )
               {
                  seed_version = boost::get<std::string>( item.second );
               }
               else if( item.first == "seed" )
               {
                  seed = boost::get<std::string>( item.second );
               }
               else if( item.first == "master_public_key" )
               {
                  masterkey = boost::get<std::string>( item.second );
               }
               else if( item.first == "accounts" )
               {
                  accounts.items = boost::get<bts::python_dict_type_t>( item.second ).items;
               }
            }
         }
         else
         {
            FC_THROW_EXCEPTION( exception, "failed to parse electrum wallet" );
         }
      }
Exemplo n.º 12
0
///////////////////////////////////////////////////////////////////////////////
//  Main program
///////////////////////////////////////////////////////////////////////////////
int
main()
{
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Expression parser...\n\n";
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Type an expression...or [q or Q] to quit\n\n";

    typedef std::string::const_iterator iterator_type;
    typedef client::ast::program ast_program;
    typedef client::ast::printer ast_print;
    typedef client::ast::eval ast_eval;

    std::string str;
    while (std::getline(std::cin, str))
    {
        if (str.empty() || str[0] == 'q' || str[0] == 'Q')
            break;

        auto& calc = client::calculator;    // Our grammar
        ast_program program;                // Our program (AST)
        ast_print print;                    // Prints the program
        ast_eval eval;                      // Evaluates the program

        iterator_type iter = str.begin();
        iterator_type end = str.end();
        boost::spirit::x3::ascii::space_type space;
        bool r = phrase_parse(iter, end, calc, space, program);

        if (r && iter == end)
        {
            std::cout << "-------------------------\n";
            std::cout << "Parsing succeeded\n";
            print(program);
            std::cout << "\nResult: " << eval(program) << std::endl;
            std::cout << "-------------------------\n";
        }
        else
        {
            std::string rest(iter, end);
            std::cout << "-------------------------\n";
            std::cout << "Parsing failed\n";
            std::cout << "stopped at: \"" << rest << "\"\n";
            std::cout << "-------------------------\n";
        }
    }

    std::cout << "Bye... :-) \n\n";
    return 0;
}
Exemplo n.º 13
0
my::interval_t interval_parse(const std::string & str)
{
  my::interval_t ret;
  interval_grammar<std::string::const_iterator> grammar;

  std::string::const_iterator beg = str.begin();
  std::string::const_iterator end = str.end();
  phrase_parse(beg, end, grammar, ascii::space, ret);
  if (beg != end) {
      throw exception("Parser error: 'interval' unexpected '%s'", std::string(beg, end).c_str());
  }

  return ret;
}
Exemplo n.º 14
0
/**
 * 指定された変数を、数値に変換する。
 *
 * @param attr_name		変数名
 * @param shape			shape
 * @return				変換された数値
 */
float Grammar::evalFloat(const std::string& attr_name, const boost::shared_ptr<Shape>& shape) const {
	myeval::calculator<std::string::const_iterator> calc;

	myeval::variables.clear();
	myeval::variables.add("scope.sx", shape->_scope.x);
	myeval::variables.add("scope.sy", shape->_scope.y);
	myeval::variables.add("scope.sz", shape->_scope.z);

	for (auto it = attrs.begin(); it != attrs.end(); ++it) {
		float val;
		if (sscanf(it->second.value.c_str(), "%f", &val) != EOF) {
			myeval::variables.add(it->first, val);
		}
	}

	float result;
	std::string::const_iterator iter = attr_name.begin();
	std::string::const_iterator end = attr_name.end();
	bool r = phrase_parse(iter, end, calc, boost::spirit::ascii::space, result);
	if (r && iter == end) {
		return result;
	} else {
		std::string rest(iter, end);
		std::cout << "Parsing failed\n";
		std::cout << "stopped at: \": " << rest << "\"\n";
		throw "Parsing failed\nstpped at: \": " + rest + "\"\n";
	}

	/*
	// To be fixed
	// 置換だと、変数BCが、変数ABCを置換してしまう。
	// 対策は?

	// scope.sx|y|zを置換
	std::string decoded_str = attr_name;
	std::string scope_x = std::to_string((long double)shape->_scope.x);
	std::string scope_y = std::to_string((long double)shape->_scope.y);
	std::string scope_z = std::to_string((long double)shape->_scope.z);
	boost::replace_all(decoded_str, "scope.sx", scope_x);
	boost::replace_all(decoded_str, "scope.sy", scope_y);
	boost::replace_all(decoded_str, "scope.sz", scope_z);

	// 変数を置換
	for (auto it = attrs.begin(); it != attrs.end(); ++it) {
		boost::replace_all(decoded_str, it->first, it->second);
	}

	return calculate(decoded_str);
	*/
}
Exemplo n.º 15
0
bool myparse(std::istream& input, const std::string filename, DataType &result)
{
    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;
    namespace classic = boost::spirit::classic;
   
    typedef std::istreambuf_iterator<char> base_iterator_type;
    base_iterator_type in_begin(input);
    
    // convert input iterator to forward iterator, usable by spirit parser
    typedef boost::spirit::multi_pass<base_iterator_type> forward_iterator_type;
    forward_iterator_type fwd_begin = boost::spirit::make_default_multi_pass(in_begin);
    forward_iterator_type fwd_end;
    
    // wrap forward iterator with position iterator, to record the position
    typedef classic::position_iterator2<forward_iterator_type> pos_iterator_type;
    pos_iterator_type position_begin(fwd_begin, fwd_end, filename);
    pos_iterator_type position_end;

    typedef forward_iterator_type used_iterator_type;
    used_iterator_type s = fwd_begin;
    used_iterator_type e = fwd_end;
    // typedef pos_iterator_type used_iterator_type;
    // used_iterator_type s = position_begin;
    // used_iterator_type e = position_end;

    qi::rule<used_iterator_type> skipper = ascii::space | 
	'#' >> *(ascii::char_ - qi::eol) >> qi::eol; // comment skipper, 

    Grammar<used_iterator_type, qi::rule<used_iterator_type> > g;
    bool r = false;
  
    try {
        r = phrase_parse(s, e, g, skipper, result);
    } catch(const qi::expectation_failure<used_iterator_type>& e)
    {
        std::stringstream msg;
        // const classic::file_position_base<std::string>& pos = e.first.get_position();
        // msg <<
        //     "parse error at file " << pos.file <<
        //     " line " << pos.line << " column " << pos.column << std::endl <<
        //     "'" << e.first.get_currentline() << "'" << std::endl <<
        //     std::setw(pos.column) << " " << "^- here";
        msg << "parse error";
        throw std::runtime_error(msg.str());
    }
    
    return r;
}
Exemplo n.º 16
0
Arquivo: main.cpp Projeto: CCJY/coliru
void parseSummandsInto(std::string const& str, std::vector<client::summand>& summands)
{
    typedef std::string::const_iterator It;
    static const client::summand_parser<It> g;

    It iter = str.begin(), 
       end = str.end();

    bool r = phrase_parse(iter, end, g, boost::spirit::ascii::space, summands);

    if (r && iter == end)
        return;
    else
        throw "Parse failed";
}
Exemplo n.º 17
0
///////////////////////////////////////////////////////////////////////////////
//  Main program
///////////////////////////////////////////////////////////////////////////////
int
main()
{
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Expression parser...\n\n";
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Type an expression...or [q or Q] to quit\n\n";

    myeval::calculator<std::string::const_iterator> calc; // Our grammar

    myeval::variables.add("PI", 3.1415923f);

    std::string str;
    float result;
    while (std::getline(std::cin, str))
    {
        if (str.empty() || str[0] == 'q' || str[0] == 'Q')
            break;

        std::string::const_iterator iter = str.begin();
        std::string::const_iterator end = str.end();
        bool r = phrase_parse(iter, end, calc, boost::spirit::ascii::space, result);

        if (r && iter == end)
        {
            std::cout << "-------------------------\n";
            std::cout << "Parsing succeeded\n";
            std::cout << "result = " << result << std::endl;
            std::cout << "-------------------------\n";
        }
        else
        {
            std::string rest(iter, end);
            std::cout << "-------------------------\n";
            std::cout << "Parsing failed\n";
            std::cout << "stopped at: \": " << rest << "\"\n";
            std::cout << "-------------------------\n";
        }
    }

    std::cout << "Bye... :-) \n\n";
    return 0;
}
Exemplo n.º 18
0
///////////////////////////////////////////////////////////////////////////////
//  Main program
///////////////////////////////////////////////////////////////////////////////
int
main()
{
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Expression parser...\n\n";
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Type an expression...or [q or Q] to quit\n\n";

    typedef std::string::const_iterator iterator_type;
    typedef client::calculator<iterator_type> calculator;

    boost::spirit::ascii::space_type space; // Our skipper
    calculator calc; // Our grammar

    std::string str;
    while (std::getline(std::cin, str))
    {
        if (str.empty() || str[0] == 'q' || str[0] == 'Q')
            break;

        std::string::const_iterator iter = str.begin();
        std::string::const_iterator end = str.end();
        bool r = phrase_parse(iter, end, calc, space);

        if (r && iter == end)
        {
            std::cout << "-------------------------\n";
            std::cout << "Parsing succeeded\n";
            std::cout << "-------------------------\n";
        }
        else
        {
            std::string rest(iter, end);
            std::cout << "-------------------------\n";
            std::cout << "Parsing failed\n";
            std::cout << "stopped at: \" " << rest << "\"\n";
            std::cout << "-------------------------\n";
        }
    }

    std::cout << "Bye... :-) \n\n";
    return 0;
}
Exemplo n.º 19
0
Arquivo: main.cpp Projeto: CCJY/coliru
int main() {
    namespace qi = boost::spirit::qi;
    namespace phx = boost::phoenix;
    using It = std::string::const_iterator;

    qi::rule<It, X(), qi::space_type> grammar;
    grammar %=
        (("value1" > qi::lit('=') > qi::int_) ^
         ("value2" > qi::lit('=') > qi::int_) ^
         ("value3" > qi::lit('=') > qi::int_) ^
         ("value4" > qi::lit('=') > qi::int_))
        >> qi::eoi [ qi::_pass = phx::bind(&X::is_valid, qi::_val) ]
        ;

    for (std::string const& input : {
            "value1 = 10\nvalue2 = 20\nvalue3 = 30\nvalue4 = 40\n",
            // Order doesn't matter but each value1 ... value4 line must be present exactly once. This would be OK:
            "value1 = 10\nvalue4 = 40\nvalue2 = 20\nvalue3 = 30\n",
            // But this would not be OK (duplicated value1):
            "value1 = 10\nvalue2 = 20\nvalue3 = 30\nvalue4 = 40\nvalue1 = 10000\n",
            // Nor this (missing value4):
            "value1 = 10\nvalue2 = 20\nvalue3 = 30\n",
            // value3 _is_ optional though:
            "value1 = 10\nvalue2 = 20\nvalue4 = 40\n",
        })
    {
        std::cout << "---------------------------------------------------------\n";
        std::cout << "Parsing '" << input << "'\n";
        auto f(input.begin()), l(input.end());
        X parsed;
        bool ok = phrase_parse(f, l, grammar, qi::space, parsed);

        if (ok) {
            std::cout << "Parsing succeeded: " << boost::fusion::as_vector(parsed) << "\n";
        } else {
            std::cout << "Parsing failed\n";
        }

        if (f!=l)
            std::cout << "Remaing input '" << std::string(f,l) << "'\n";
    }
}
Exemplo n.º 20
0
	boost::optional<
		ast::statement_list
	> parser<Iterator>::parse_impl(Iterator first, Iterator last)
	{
		dynamo::parse::statement<	
			Iterator
		> stmt(indexed_source_, sink_);

		boost::spirit::ascii::space_type space;
		dynamo::ast::statement_list ast;
		
		indexed_source_.begin_parse(first, last);

		bool r = phrase_parse(first, last, +stmt, space, ast);
		
		if(r && first == last)
		{
			return ast;
		}
		return boost::none;
	}
Exemplo n.º 21
0
    bool compile(Grammar const& calc, std::string const& expr)
    {
        std::string::const_iterator iter = expr.begin();
        std::string::const_iterator end = expr.end();
        bool r = phrase_parse(iter, end, calc, ascii::space);

        if (r && iter == end)
        {
            std::cout << "-------------------------\n";
            std::cout << "Parsing succeeded\n";
            std::cout << "-------------------------\n";
            return true;
        }
        else
        {
            std::cout << "-------------------------\n";
            std::cout << "Parsing failed\n";
            std::cout << "-------------------------\n";
            return false;
        }
    }
Exemplo n.º 22
0
void LocalForwarder::getHeadersHandle(const boost::system::error_code& e) {
    if (e) {
        LOG_ACPROXY_ERROR("get http request header error ", e.message());
        //conn_->close();
        return;
    }

    LOG_ACPROXY_INFO("start reading http request headers...");

    char buf[1024];  // XXX

    auto fd = socket_->native_handle();
    ssize_t sz = ::recv(fd, buf, sizeof(buf), MSG_PEEK);
    LOG_ACPROXY_DEBUG("sz of read http request header = ", sz);
    if (sz < 0) {
        const int err = errno;
        if (err == EAGAIN || err == EWOULDBLOCK) {
            LOG_ACPROXY_INFO("read http request header again...");
            getHeaders();
            return;
        }
        LOG_ACPROXY_INFO("read http request header error");
        //conn_->close();
        return;
    } else if (sz == 0) {
        LOG_ACPROXY_INFO("client close socket");
        //conn_->close();
        return;
    }
    const char* pos = (const char*)::memmem(buf, sz, "\r\n\r\n", 4);

    bool found = pos;
    ssize_t diff = (found ? pos - buf + 4 : sz);
    if (!found) {
        // \r | \n\r\n
        if (headers.size() >= 1 && headers.back() == '\r' && sz >= 3 &&
            buf[0] == '\n' && buf[1] == '\r' && buf[2] == '\n') {
            found = true;
            diff = 3;
        }

        // \r\n | \r\n
        if (headers.size() >= 2 && headers[headers.size() - 2] == '\r' &&
            headers[headers.size() - 1] == '\n' && sz >= 2 && buf[0] == '\r' &&
            buf[1] == '\n') {
            found = true;
            diff = 2;
        }

        // \r\n\r | \n
        if (headers.size() >= 3 && headers[headers.size() - 3] == '\r' &&
            headers[headers.size() - 2] == '\n' &&
            headers[headers.size() - 1] == '\r' && sz >= 1 && buf[0] == '\n') {
            found = true;
            diff = 1;
        }
    }

    // consume
    ::recv(fd, buf, diff, 0);
    headers.insert(headers.end(), buf, buf + diff);
    if (found) {
        Http::RequestHeaderGrammar<decltype(headers)::iterator> grammar;
        bool res = phrase_parse(headers.begin(), headers.end(), grammar,
                                boost::spirit::qi::ascii::blank, request_);
        if (!res) {
            LOG_ACPROXY_ERROR("parse http request header error");
            //conn_->close();
            return;
        }

        request_.rewrite();
        request_.setKeepAlive(false);

        // cache layer
        if (request_.method == "GET" || request_.method == "HEAD") {
            std::string key = keygen(request_.getHost(), request_.getPort(),
                                     request_.uri, request_.method);
            auto& cache = getGlobalCache();
            if (boost::optional<std::string> resp = cache.get(key)) {
                LOG_ACPROXY_INFO("hit, found in cache!");
                finish(resp.value());
                return;
            }
            if (auto c = conn_.lock()) {
                c->getRemoteForwarder()->setCacheKey(key);
            } else {
                LOG_ACPROXY_WARNING("connection object is freed");
                return;
            }
        }

        // LOG_ACPROXY_DEBUG("request = \n", request_.toBuffer());

        if (!request_.hasResponseBody()) {
            if (auto c = conn_.lock()) {
                c->getRemoteForwarder()->setResponseBody(false);
            } else {
                LOG_ACPROXY_WARNING("connection object is freed");
                return;
            }
        }

        std::string host = request_.getHost();
        int port = request_.getPort();
        if (auto c = conn_.lock()) {
            res = c->getRemoteForwarder()->connect(host, port);
        } else {
            LOG_ACPROXY_WARNING("connection object is freed");
            return;
        }
        if (!res) {
            if (auto c = conn_.lock()) {
                c->report("failure", {{"host", boost::asio::ip::host_name()}},
                          std::time(0));
            }
            // XXX Maybe shutdowning socket is better
            LOG_ACPROXY_INFO("connection timeout, close it");
            //send("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
            //conn_->close();
            return;
        }
        LOG_ACPROXY_DEBUG("connection complete");

        if (!request_.isConnectMethod()) {
            // forward header to server
            if (auto c = conn_.lock()) {
                c->getRemoteForwarder()->send(request_.toBuffer());
            } else {
                LOG_ACPROXY_WARNING("connection object is freed");
                return;
            }
        } else {
            // no parse response header, get rawdata and forward instead
            if (auto c = conn_.lock()) {
                c->getRemoteForwarder()->setParseResponseHeader(false);
            } else {
                LOG_ACPROXY_WARNING("connection object is freed");
                return;
            }
            // send a fake 200 response in tunnel mode
            send("HTTP/1.1 200 Connection Established\r\n\r\n");
        }

        if (request_.hasContentBody()) {
            getBody();
        }
    } else {
        // request header is incomplete, read again
        LOG_ACPROXY_INFO("http request header incomplete, read again");
        getHeaders();
    }
    if (auto c = conn_.lock()) {
        c->update();
    } else {
        LOG_ACPROXY_WARNING("connection object is freed");
        return;
    }
}
Exemplo n.º 23
0
int main()
{
	typedef std::string::const_iterator iterator_type;
	typedef record_parser<iterator_type> record_parser;

	record_parser g;
	dtcc::database::record result;
	iterator_type iter = rec.begin();
	iterator_type end = rec.end();

	if (phrase_parse(iter, end, g, ascii::space, result) && iter == end)
	{
		std::cout << "-------------------------\n";
		std::cout << "Parsing succeeded\n";
		std::cout << "DISSEMINATION_ID: " << result.DISSEMINATION_ID << std::endl;

		if (!result.ORIGINAL_DISSEMINATION_ID)
		{
			std::cout << "ORIGINAL_DISSEMINATION_ID: " << "(none)" << std::endl;
		}
		else
		{
			std::cout << "ORIGINAL_DISSEMINATION_ID: " << result.ORIGINAL_DISSEMINATION_ID << std::endl;
		}

		std::cout << "ACTION: " << result.ACTION << std::endl;
		std::cout << "EXECUTION_TIMESTAMP: " << result.EXECUTION_TIMESTAMP << std::endl;
		std::cout << "CLEARED: " << result.CLEARED << std::endl;

		std::cout << "INDICATION_OF_COLLATERALIZATION: " << result.INDICATION_OF_COLLATERALIZATION << std::endl;
		if (!result.INDICATION_OF_END_USER_EXCEPTION)
			std::cout << "INDICATION_OF_END_USER_EXCEPTION: (none)" << std::endl;
		else
			std::cout << "INDICATION_OF_END_USER_EXCEPTION: " << result.INDICATION_OF_END_USER_EXCEPTION.get() << std::endl;

		std::cout << "INDICATION_OF_OTHER_PRICE_AFFECTING_TERM: " << result.INDICATION_OF_OTHER_PRICE_AFFECTING_TERM << std::endl;
		std::cout << "BLOCK_TRADES_AND_LARGE_NOTIONAL_OFFFACILITY_SWAPS: " << result.BLOCK_TRADES_AND_LARGE_NOTIONAL_OFFFACILITY_SWAPS << std::endl;

		//if (!result.EXECUTION_VENUE)
		//	std::cout << "EXECUTION_VENUE: (none)" << std::endl;
		//else
		//	std::cout << "EXECUTION_VENUE: " << result.EXECUTION_VENUE.get() << std::endl;

		if (!result.EFFECTIVE_DATE)
		{
			std::cout << "EFFECTIVE_DATE: " << "(none)" << std::endl;
		}
		else
		{
			std::cout << "EFFECTIVE_DATE: " << result.ORIGINAL_DISSEMINATION_ID << std::endl;
		}

		if (!result.END_DATE)
		{
			std::cout << "END_DATE: " << "(none)" << std::endl;
		}
		else
		{
			std::cout << "END_DATE: " << result.ORIGINAL_DISSEMINATION_ID << std::endl;
		}

		std::cout << "\n-------------------------\n";
	}
	else
	{
		std::cout << "-------------------------\n";
		std::cout << "Parsing failed\n";
		std::cout << "-------------------------\n";
	}

	system("pause");
	return 0;
}
Exemplo n.º 24
0
///////////////////////////////////////////////////////////////////////////////
//  Main program
///////////////////////////////////////////////////////////////////////////////
int
main()
{
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Statement parser...\n\n";
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "Type some statements... ";
    std::cout << "An empty line ends input, compiles, runs and prints results\n\n";
    std::cout << "Example:\n\n";
    std::cout << "    var a = 123;\n";
    std::cout << "    var b = 456;\n";
    std::cout << "    var c = a + b * 2;\n\n";
    std::cout << "-------------------------\n";

    std::string str;
    std::string source;
    while (std::getline(std::cin, str))
    {
        if (str.empty())
            break;
        source += str + '\n';
    }

    typedef std::string::const_iterator iterator_type;
    iterator_type iter = source.begin();
    iterator_type end = source.end();

    client::vmachine vm;                        // Our virtual machine
    client::code_gen::program program;          // Our VM program
    client::ast::statement_list ast;            // Our AST

    client::error_handler<iterator_type>
        error_handler(iter, end);               // Our error handler
    client::parser::statement<iterator_type>
        parser(error_handler);                  // Our parser
    client::code_gen::compiler
        compile(program, error_handler);       // Our compiler

    boost::spirit::ascii::space_type space;
    bool success = phrase_parse(iter, end, parser, space, ast);

    std::cout << "-------------------------\n";

    if (success && iter == end)
    {
        if (compile.start(ast))
        {
            std::cout << "Success\n";
            std::cout << "-------------------------\n";
            vm.execute(program());

            std::cout << "-------------------------\n";
            std::cout << "Assembler----------------\n\n";
            program.print_assembler();

            std::cout << "-------------------------\n";
            std::cout << "Results------------------\n\n";
            program.print_variables(vm.stack);
        }
        else
        {
            std::cout << "Compile failure\n";
        }
    }
    else
    {
        std::cout << "Parse failure\n";
    }

    std::cout << "-------------------------\n\n";
    return 0;
}
Exemplo n.º 25
0
Arquivo: main.cpp Projeto: CCJY/coliru
 bool Parse(It begin, It end, Sequence& ret)
 {
     static Grammar<It> grammar;
     return phrase_parse(begin, end, grammar, blank, ret);
 }
Exemplo n.º 26
0
void BURuleInputParser::read_rulefile(const std::string& filename,
				      std::vector<LexicalRule>& lexicals,
				      std::vector<URule>& unaries,
				      std::vector<BRule>& n_aries,
                                      std::map<short, unsigned short>& num_annotations_map,
                                      std::vector< Tree<unsigned> >& history_trees
				      ) throw(ParseError)
{
  std::ifstream in_file(filename.c_str(),std::ios::in);

  if (!in_file)
  {
    std::cerr << "can't open file: " + filename  << std::endl;
    exit(1);
  }

  std::string str;

  in_file.unsetf(std::ios::skipws); // No white space skipping!
  std::copy(
	    std::istream_iterator<char>(in_file),
	    std::istream_iterator<char>(),
	    std::back_inserter(str));


  std::string::const_iterator iter = str.begin();
  std::string::const_iterator end = str.end();

  typedef std::string::const_iterator iterator_type;
  typedef burule_parser<iterator_type> parser;
  typedef annotation_map_parser<iterator_type> am_parser;
  typedef ptbpstree_parser<iterator_type> tree_parser;

  parser p;
  am_parser a;
  tree_parser t;

  bool res;

  // Read annotations Map
  // lines like: Symbol Num_annot
  do {
    std::pair<int,unsigned> m;
    res = phrase_parse(iter, end, a, mychar::space, m);
    num_annotations_map.insert(m);
  } while(res && iter != end);

  do {
    res = phrase_parse(iter, end, t, mychar::space, history_trees);
  } while (res && iter != end);


  // Read rules
  do {
    //std::cout << "in rule parser" << std::endl;
    AnnotatedRule * r;
    res = phrase_parse(iter, end, p, mychar::space, r);

    if(!res) {
      //std::cout << "not read: " << std::string(iter,end) << std::endl;
      throw(ParseError(filename));
    }

    if(r->is_lexical()) {
      if(static_cast<LexicalRule*>(r)->get_probability().size()>0)
	lexicals.push_back(*(static_cast<LexicalRule*>(r)));
    }
    else
      if(r->is_unary()) {
	if(static_cast<URule*>(r)->get_probability().size()>0)
	  unaries.push_back(*static_cast<URule*>(r));
      }
      else
	if(static_cast<BRule*>(r)->get_probability().size()>0)
	  n_aries.push_back(*static_cast<BRule*>(r));

    delete(r);
  } while(res && iter != end);
  //std::cout << "got here " << std::endl;
  in_file.close();
}