473,657 Members | 2,624 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reg parser for interpretor pattern in C++

Hello,
I am working on a problem where I will have a boolean expression
with
upto four variables: A,B,C,D and connected by basic operator &&,||and
may be XOR and NOT in future AND has higher precedence than OR and ()
(parenthesis) takes utmost precedence... I wrote a sample code that
uses interpretor pattern that uses composition pattern to repeatedly
call the evaluate() function, this works properly, however I need to
construct the expression object properly, I hardcoded this (as shown
in the sample code attached below) but would assume I should some
kind
of parsing technique to generate the proper top level expression
object, I have no background in Computer Science (am an electrical
enginner :)) so would need some help here, how to build this parser,
I
GOGled quite a bit and found some info but nothing simple/straight
forward to understand, any pointers on simple layman tuorials/sample
code for this problem would be highly appreciated:

My other question is: is it an overkill to even think of using the
interpretor pattern for problem I am trying to solve, if its OK, is
it
overkill to try building parser is it enough to hardcode the
generation of expression object...
Thanks,
Sunil
P.S.: My interpretor pattern below doesnt need to pass around the
"context" as the object Variable is already updated externally...
Sample code:
//Variable: smallest thing that can be part of expression.
class Variable {
public:
Variable(bool value,string name):_value(va lue),_name(name ) {
}
bool getValue() {
return _value;
}
void setValue(bool value) {
_value=value;
}
string getName() {
return _name;
}
private:
bool _value;
std::string _name;

};
enum
OperatorType{OP ERATOR_NONE,AND _OPERATOR,OR_OP ERATOR,NOT_OPER ATOR};

//Expression is built using variables and symbols and it can be
recursive i.e.
//an expression can be having expression in itself. It can have 1 or
two
//operands but only one operator
class Expression {
public:
Expression(stri ng exprName,Operat orType
operatorType) :_exprName(expr Name),_operator (operatorType) {}
~Expression(){}
string getName() {
return _exprName;
}
virtual bool evaluate()=0;
protected:
string _exprName;
OperatorType _operator;

};
//Various basic expressions allowed: AND,OR
//AND
class AndExpression: public Expression {
public:
AndExpression(E xpression* exp1,Expression * exp2,string exprName):
Expression(expr Name,AND_OPERAT OR),_exp1(exp1) ,_exp2(exp2) {

}
bool evaluate() {
bool retVal;
cout << "Evaluating variable AND expr: name=" << _exprName <<
endl;
retVal = (_exp1->evaluate() && _exp2->evaluate());
cout << "Result of AND expr:" << _exprName << "is:" <<retVal <<
endl;
return retVal;
}
private:
Expression * _exp1;
Expression * _exp2;

};
//OR
class ORExpression: public Expression {
public:
ORExpression(Ex pression* exp1,Expression *exp2,string exprName):
Expression(expr Name,OR_OPERATO R),_exp1(exp1), _exp2(exp2) {

}
bool evaluate() {
bool retVal,exp1Val;
cout << "Evaluating variable OR expr: name=" << _exprName <<
endl;
retVal=(_exp1->evaluate() || _exp2->evaluate());
cout << "Result of OR expr:" << _exprName << " is:" << retVal <<
endl;
return retVal;
}
private:
Expression* _exp1;
Expression* _exp2;

};
//NOT
class NOTExpression: public Expression {
public:

NOTExpression(E xpression* exp,string exprName):
Expression(expr Name,NOT_OPERAT OR),_exp(exp) {
}
bool evaluate() {
bool retVal;
cout << "Evaluating variable NOT expr: name=" << _exprName <<
endl;
retVal = !(_exp->evaluate());
cout << "Result of NOT expr:" << _exprName << " is " << retVal;
return retVal;
}
private:
Expression* _exp;

};
//VariableExpress ion: expression with variable.
class VariableExpress ion: public Expression {
public:
VariableExpress ion(Variable* var): Expression(var->getName()
+"expr",OPERATO R_NONE),_var(va r) {
}
bool evaluate() {
cout << "Evaluating variable expr: name=" << _exprName
<< "value= "
<< _var->getValue() <<endl;
return _var->getValue();
}
private:
Variable* _var;
};
int main() {
Variable var1(false,"var 1");
Variable var2(true,"var2 ");
Variable var3(true,"var3 ");
VariableExpress ion varExp1(&var1);
VariableExpress ion varExp2(&var2);
VariableExpress ion varExp3(&var3);
//(varExp1 || varExp2) && varExp3
Expression *exp = new AndExpression(n ew
ORExpression(&v arExp1,&varExp2 ,"inexp"),&varE xp3,"outexp");
cout << "Result of evaluation=" << exp->evaluate() << endl;
var2.setValue(f alse);
cout << "Result of evaluation=" << exp->evaluate() << endl;
//Advantage of this approach A||B&C factored in when expression
created.
Jun 27 '08 #1
1 1748
sunil wrote:
Hello,
I am working on a problem where I will have a boolean expression
with
upto four variables: A,B,C,D and connected by basic operator &&,||and
may be XOR and NOT in future AND has higher precedence than OR and ()
(parenthesis) takes utmost precedence... I wrote a sample code that
uses interpretor pattern that uses composition pattern to repeatedly
call the evaluate() function, this works properly, however I need to
construct the expression object properly, I hardcoded this (as shown
in the sample code attached below) but would assume I should some
kind
of parsing technique to generate the proper top level expression
object, I have no background in Computer Science (am an electrical
enginner :)) so would need some help here, how to build this parser,
I
GOGled quite a bit and found some info but nothing simple/straight
forward to understand, any pointers on simple layman tuorials/sample
code for this problem would be highly appreciated:

My other question is: is it an overkill to even think of using the
interpretor pattern for problem I am trying to solve, if its OK, is
it
overkill to try building parser is it enough to hardcode the
generation of expression object...
Thanks,
Sunil
Hello Sunil, the technique you are looking for is called 'expression
template' in C++, a form of template metaprogramming . The basic concept
is very simple, but of course you will need to work out the details. If
you requirement is more than parsing simple expression, then you should
also take a look at boost::spirit to build embedded parser in C++.

Fei
Jun 27 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1373
by: Balaji | last post by:
Hello Everyone.... I have created a simple GUI using wx python. Its an simple editor... Now what I want to do is pass the contents of this editor and receive solution from python. Suppose in the editor if I say x=2 and y=3 and then x+y I should get back the solution.
1
1457
by: Azeem M. Suleman | last post by:
Hello, I need to use Csharp compiler and an interpretor. In my application user will use the application and application will write CSharp code on backend. But now i don't need to reinvent the wheel, just need to know how i can give user an option to build the project which will compile and make an executable file. thanks.
3
1954
by: cr88192 | last post by:
for various reasons, I added an imo ugly hack to my xml parser. basically, I wanted the ability to have binary payload within the xml parse trees. this was partly because I came up with a binary xml format (mentioned more later), and thought it would be "useful" to be able to store binary data inline with this format, and still wanted to keep things balanced (whatever the binary version can do, the textual version can do as well). the...
4
3086
by: billcoumbe | last post by:
any recommendations? I'm looking for something that will just run from the unix command line to validate large (20-50Mb) XML files against an XML DTD. Ideally something that is actively supported and has good documentation! If there's nothing suitable for Solaris a command line program for Windows might do - currently using XMetaL/XMLSpy parsers which aren't really suited to large files.
9
1716
by: Azeem M. Suleman | last post by:
Hello, I need to use Csharp compiler and an interpretor. In my application user will use the application and application will write CSharp code on backend. But now i don't need to reinvent the wheel, just need to know how i can give user an option to build the project which will compile and make an executable file. thanks.
4
2805
by: siddharthkhare | last post by:
Hi All, I need to parse certain text from a paragraph (like 20 lines). I know the exact tags that I am looking for. my approach is to define a xml (config) file that defines what tag I am looking for and corresponding regular expression to search for the pattern. Xml file will also have a way to say what should be the pervious tag
9
3606
by: Henrik Goldman | last post by:
Hi, I would like to create a simplistic parser which goes through each .h file and finds each function prototype (or inline implementation) along with class names and member functions. Examples: test.h:
3
2180
by: stephen.nil | last post by:
http://code.google.com/p/spxml/ http://spxml.googlecode.com/files/spxml-0.1.src.tar.gz Simple Plain Xml Parser (spxml) is a simple and plain stream-oriented XML parser that supports pull-model and DOM-model XML parsing. As the user passes it chunks of an XML document, it identifies elements, character data, or other entities and return the appropriate event. Chunks can range from one byte to the whole XML document and can safely be read...
7
1663
by: Samuel | last post by:
Hi, How would you implement a simple parser for the following string: --- In this string $variable1 is substituted, while \$variable2 is not. --- I know how to write a parser, but I am looking for an elegant (and lazy) way. Any idea?
0
8330
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8850
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8523
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8626
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7355
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4334
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1975
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.