2 * Copyright (C) 2017 Cisco Inc.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License, version 2,
6 * as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 // @author Changxue Deng <chadeng@cisco.com>
24 #include "expr_parser.h"
27 ExprParser::ExprParser(const std::string &exp)
34 ExprParser::~ExprParser()
38 int ExprParser::Evaluate(std::string &result)
41 int rval = Parse(result);
44 std::cout << err_str << "\n";
46 else if(rval == 0 && pos < expr.length())
48 std::cout << "extra string " + expr.substr(pos)
49 << " found at the end of expression\n";
61 // E ---> T + E (NOT IMPLEMENTED YET)
62 // T ---> literal string
64 // literal string: 'abcdefg'
65 // convert hex to binary: bin('0001ff01')
66 // convert hex to binary and back to hex:
67 // hex(bin('4da32feebf1611e7bd98c0b13cdb778c'))=='4da32feebf1611e7bd98c0b13cdb778c'
68 int ExprParser::Parse(std::string &result)
70 if(pos >= expr.length())
77 if(expr.find("in(", pos+1, 3) == std::string::npos)
79 err_str = "unrecognized expression " + expr.substr(pos);
88 err_str = "missing ) at the end of " + expr.substr(0, pos);
92 rval = hex_2_bin(result.c_str(), result.length(), buffer,
93 EXPR_PARSER_BUFFER_SIZE);
96 err_str = "failed to convert hex string " + result + " to binary format";
99 result = std::string((char *)buffer, rval);
102 if(expr.find("ex(", pos+1, 3) == std::string::npos)
104 err_str = "unrecognized expression " + expr.substr(pos);
108 rval = Parse(result);
113 err_str = "missing ) at the end of " + expr.substr(0, pos);
117 rval = bin_2_hex((const uint8_t *)result.data(), result.size(),
118 (char *)buffer, EXPR_PARSER_BUFFER_SIZE);
121 err_str = "failed to convert binary string to hex";
124 result = std::string((char *)buffer, rval);
128 size_t endp = expr.find('\'', pos+1);
129 if(endp == std::string::npos)
131 err_str = "expression " + expr.substr(0, pos) + " missing closing \'";
134 result = expr.substr(pos+1, endp-pos-1);
139 err_str = "unrecognized expression " + expr.substr(pos) + "\n";