ATLAS Offline Software
Loading...
Searching...
No Matches
ExpressionParser.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2021 CERN for the benefit of the ATLAS collaboration
3*/
4
6// ExpressionParser.cxx, (c) ATLAS Detector software
8// Author: Thomas Gillam (thomas.gillam@cern.ch)
9// ExpressionParsing library
11
13#include "ParsingInternals.h"
16
17#include <boost/algorithm/string.hpp>
18
19namespace ExpressionParsing {
20
27
34
41
43 {
44 m_proxyLoader = proxyLoader;
45 m_unitInterpreter = unitInterpreter;
46 setup();
47 }
48
50 {
51 if (m_vm) {
52 delete m_vm;
53 }
54 }
55
57 {
58 m_vm = new VirtualMachine();
59 }
60
61 bool ExpressionParser::loadExpression(const std::string &expression)
62 {
63 std::string trimmedExpression = boost::algorithm::trim_copy_if(expression, boost::is_any_of("\""));
64
66 m_code.clear();
67
68 Grammar<std::string::const_iterator> grammar;
69 ast::expression expr;
70
71 std::string::const_iterator expressionIter = trimmedExpression.begin();
72 std::string::const_iterator expressionEnd = trimmedExpression.end();
73 using boost::spirit::ascii::space_type;
74 bool r = phrase_parse(expressionIter, expressionEnd, grammar, space_type(), expr);
75 std::string remainingExpression(expressionIter, expressionEnd);
76 boost::trim(remainingExpression);
77 if (remainingExpression.length() > 0) {
78 throw std::runtime_error("Did you forget an operator? This was not parsed: '" + remainingExpression +"'");
79 }
80
81 if (!r) return false;
82
83 Compiler compiler(m_code, m_proxyLoader, m_unitInterpreter);
84 compiler(expr);
85
86 return true;
87 }
88
89 std::vector<std::string> ExpressionParser::getVariables() const {
90 std::vector<std::string> vars;
91 for (const StackElement &element : m_code) {
92 if (element.isProxy() && std::find(vars.begin(),vars.end(),element.proxyVarName()) == vars.end() ) {
93 vars.push_back( element.proxyVarName() );
94 }
95 }
96 return vars;
97 }
98
100 {
101 return m_vm->execute(m_code);
102 }
103
105 {
107 if (result.isScalar()) return result.asBool();
108 else throw std::runtime_error("Unable to evaluate vector quantity as a boolean");
109 }
110
112 {
114 if (result.isScalar()) return result.scalarValue<double>();
115 else throw std::runtime_error("Unable to evaluate vector quantity as a double");
116 }
117
118 std::vector<int> ExpressionParser::evaluateAsVector() const
119 {
121 if (result.isVector()) return result.vectorValue<int>();
122 else throw std::runtime_error("Unable to evaluate scalar quantity as a vector");
123 }
124}
std::vector< StackElement > m_code
std::vector< int > evaluateAsVector() const
bool loadExpression(const std::string &expression)
std::vector< std::string > getVariables() const
Class describing a single element in a text expression.
int r
Definition globals.cxx:22
Namespace holding all the expression evaluation code.