UnitEvaluator.cc
Go to the documentation of this file.
1 #include <utl/UnitEvaluator.h>
2 #include <utl/ErrorLogger.h>
3 #include <utl/AugerException.h>
4 
5 #include <boost/version.hpp>
6 #if BOOST_VERSION >= 103800
7 # define BOOST_SPIRIT_USE_OLD_NAMESPACE
8 # include <boost/spirit/include/classic_parser.hpp>
9 #else
10 # include <boost/spirit/core/parser.hpp>
11 #endif
12 
13 #include <iostream>
14 #include <iomanip>
15 #include <sstream>
16 #include <string>
17 
18 using namespace std;
19 
20 
21 namespace utl {
22 
23  string
24  UnitEvaluator::GetError()
25  const
26  {
27  ostringstream errStream;
28  errStream << "Unit parsing failed: ";
29  switch (fError) {
30  case UnitGrammar::eLookup:
31  errStream << "Unknown unit in the expression.";
32  break;
33  case UnitGrammar::eBracket:
34  errStream << "Not a well-formed expression. (e.g.: brackets)";
35  break;
36  case UnitGrammar::eBadSymbol:
37  errStream << "Invalid symbol in the expression. (e.g.: + or -)";
38  break;
39  case UnitGrammar::eParsing:
40  errStream << "Boost spirit parsing error.";
41  break;
42  default: //Should never reach this.
43  errStream << "Unknown error.";
44  break;
45  }
46  errStream << '\n' << fExpression << '\n'
47  << setw(fErrPosition) << " "
48  << "^ failed at the " << fErrPosition+1 << ". position\n";
49  return errStream.str();
50  }
51 
52 
53  double
54  UnitEvaluator::Evaluate(const string& expression)
55  const
56  {
57  fExpression = expression;
58  fError = UnitGrammar::eOk;
59  fErrPosition = 0;
60 
61  string::iterator firstChar = fExpression.begin();
62  const string::iterator lastChar = fExpression.end();
63 
64  boost::spirit::parse_info<string::iterator> info;
65 
66  do {
67  info = boost::spirit::parse(
68  firstChar,
69  lastChar,
70  fGrammar,
71  boost::spirit::space_p
72  );
73 
74  if (!info.hit) { //not successful parsing
75  fError = UnitGrammar::eParsing;
76  fErrPosition = info.stop - firstChar;
77  const char errChar = fExpression[fErrPosition];
78  if (errChar == '-' || errChar == '+')
79  fError = UnitGrammar::eBadSymbol;
80  if (errChar == '(' || errChar == ')')
81  fError = UnitGrammar::eBracket;
82  firstChar = info.stop; //next start point
83  } else if (!info.full) { //ok, but if no full match
84  fError = UnitGrammar::eBracket;
85  fErrPosition = 0;
86  }
87  } while(!info.full && info.hit); //full match and parsing is ok
88 
89  if (fError != UnitGrammar::eOk) {
90  const string err = GetError();
91  ERROR(err);
92  throw XMLParseException(err);
93  }
94 
95  return fValue;
96  }
97 
98 }
Exception for errors encountered when parsing XML.
#define ERROR(message)
Macro for logging error messages.
Definition: ErrorLogger.h:165

, generated on Tue Sep 26 2023.