473,775 Members | 2,263 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

parsing tree help

Guys,
I am trying to build a Parse Tree with the following grammar. I have
implemented my insertions using a standard binary tree inserting
algorithm. With the psuedocode below, can you guys provide any helpful
feedback to placing insert statements into building nodes of the tree.
Any suggestions on how to build the tree will be appreciated.
I hope to build the tree to look like that
5+4

Goal
|
|
|
Expr
|
|
Term
|
Factor
|
|
+
/ \
5 4

eprime()
/*Expr' -+ Term Expr' */
/* Expr' -- Term Expr'*/

if(word = t or word = -) then
word <-NextWord()
if(Term()=false )
then return false;
else return Eprime();
/*Expr' -Empty Set */
return true;
Term()
/*Term -Factor Term'*/
if(factor()=fal se)
then return false
else return Tprime()
Tprime ()
/* Term' -x factor Term' */
/*Term' -/ factor Term'*/
if (word = x or word = / )
Word=NextWord()
if(factor () = false)
then return false;
then return TPrime();
/*Term' -Empty Set */
return True;
Factor()
/*Factor -(Expr) */
if(word = '(' ) then
word<-Nextword();
if(Expr()-false)
then return false
else if (word != ')') then
return false;
/*Factor ->Num*/
/*Factor->ident*/

else if(word!= Num and word != ident) then
report syntax error
return false;

word <- Nextword()
return true;

Main()
/* goal-Expr */
Word <-Nextword()
if(expr() and word=eof)
then proceed to the next step
else return false

Expr()
/*Expr -Term Expr' */
if(Term ()= false)
then return false
else return Eprime()
Mar 30 '08 #1
2 4443

"uche" <ur***********@ hotmail.comwrot e in message
news:1a******** *************** ***********@c19 g2000prf.google groups.com..
I am trying to build a Parse Tree with the following grammar. I have
implemented my insertions using a standard binary tree inserting
algorithm. With the psuedocode below, can you guys provide any helpful
feedback to placing insert statements into building nodes of the tree.
Any suggestions on how to build the tree will be appreciated.
I hope to build the tree to look like that
5+4
expressions, terms and factors are parse level concepts.
The important step in the parser is that

1 + ? = 1 + expression

(?) = (expression)

Thus the code is mutually recursive.

To build a tree, define

typedef struct parsenode
{
struct parse node *left;
struct parsenode *right;
char operation; /* +, - * etc, including a code for "brackets" */
double val; /* only used for leaf nodes */
} PARSENODE;

Now make expression(), facor() and and term() all return PARSENODE *s.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
Mar 30 '08 #2

"uche" <ur***********@ hotmail.comwrot e in message
news:1a******** *************** ***********@c19 g2000prf.google groups.com...
Guys,
I am trying to build a Parse Tree with the following grammar. I have
implemented my insertions using a standard binary tree inserting
algorithm. With the psuedocode below, can you guys provide any helpful
feedback to placing insert statements into building nodes of the tree.
Any suggestions on how to build the tree will be appreciated.
I hope to build the tree to look like that
5+4

I've put together the code below.

Whether it is any use to you, I don't know. It was an interesting Sunday
morning exercise.

Input is A*(B+5) (as a array of tokens). This is converted to a tree
(pointers to node structs).

Output is the tree linearised back into (A*(B+5)) (notice there are extra
parentheses here).

Output into your graphical form is fiddly but I don't think difficult (but I
haven't tried it). It's a lot easier if A+B for example can be shown like
this:

+
A
B

Then it's fairly trivial.

Hope this helps.

Bart.
/*
Convert tokenised expression into simple tree form.
Input is from array exprdata, containing the expression as a series of
tokens. (Converting from string to tokens is a separate exercise!).
printexprdata() is test function to ensure exprdata is valid.

printtree() converts tree back into linear form. Because parentheses are
not
stored in the tree (only implied), these are added here, more than
necessary however.
Printing the tree as a graph is also a separate (but simpler?) exercise.

Expressions can consist of: +, -, *, /, integer constant, (, ), and single
letter
identifiers. Also - can be used to negate (converted to own token negtoken
in tree).

*/

#include <stdio.h>
#include <stdlib.h>

typedef struct snode {
int token; /* numtoken/idtoken mean terminal node */
int value;
struct snode *left, *right;
} node;

#define endcase break;

#define addtoken 1
#define subtoken 2
#define multoken 3
#define divtoken 4
#define leftbtoken 5
#define rightbtoken 6
#define numtoken 7
#define idtoken 8
#define endtoken 9
#define badtoken 10
#define negtoken 11

node* readexpr(void);
node* readfactor(void );
node* readterm(void);
void nexttoken(void) ;
node* newnode(int,int ,node*, node*);
void printtree(node* );
void printexprdata(v oid);

int exprdata[] = /* A*(B+5) note: 1-based */
{0,idtoken, 'A', multoken, leftbtoken,idto ken, 'B', addtoken, numtoken, 5,
rightbtoken,end token};

int tokenno; /* index into exprdata */
int token; /* current token */
char *opnames = "?+-*/?????"; /* also 1-based */

/**** MAIN ****/
int main(void){
node* expr;

tokenno=1;

nexttoken();

expr=readexpr() ;

printf("Input = ");
printexprdata() ;

printf("Output = ");
printtree(expr) ;
puts("");

} /* END MAIN */
/* READEXPR */
node* readexpr() {
// term + term or term - term
node *lhs, *rhs;
int t;

lhs=readfactor( );

while (token==addtoke n || token==subtoken ) {
t=token;
nexttoken();
rhs=readfactor( );

lhs=newnode(t, 0, lhs, rhs);
};
return lhs;
}

/* READFACTOR */
node* readfactor() {
// factor * factor or factor/factor
node *lhs, *rhs;
int t;

lhs=readterm();

while (token==multoke n || token==divtoken ) {
t=token;
nexttoken();
rhs=readterm();
lhs=newnode(t, 0, lhs, rhs);
};
return lhs;
}

/* READTERM */
node* readterm() {
// number or -term or (expr)
node *term;
int t;

switch (token) {
case subtoken:
nexttoken();
return newnode(negtoke n, 0, readterm(), NULL);

case leftbtoken:
nexttoken();
term=readexpr() ;
if (token!=rightbt oken)
return newnode(badtoke n, 0, NULL, NULL);
nexttoken();
return term;

case numtoken: case idtoken:
t=token;
nexttoken();
term=newnode(t, token, NULL, NULL);
nexttoken();
return term;

default:
return newnode(badtoke n, 0, NULL, NULL);
};
}

/* NEXTTOKEN */
void nexttoken() {
token=exprdata[tokenno];
if (token!=endtoke n) ++tokenno;
}

/* NEWNODE */
node * newnode(int opc, int value, node* left, node *right) {
node* p;

p=malloc(sizeof (node));

if (p==NULL) {
puts("Expr too complex.");
exit(1);
};

p->token=opc;
p->value=value;
p->left=left;
p->right=right;
return p;
}

/* PRINTTREE */
void printtree(node *expr) {

switch (expr->token) {
case numtoken:
printf("%d",exp r->value);
endcase

case idtoken:
printf("%c",exp r->value);
endcase

case negtoken:
printf("-");
printtree(expr->left);
endcase

case badtoken:
printf("Error") ;
endcase

default:
printf("(");
printtree(expr->left);
printf("%c",opn ames[expr->token]);
printtree(expr->right);
printf(")");
};

}

/* FOR TESTING EXPRDATA[] */
void printexprdata() {
int n;

n=1;

while (n<=(sizeof(exp rdata)/sizeof(exprdata[0]))) {

switch(exprdata[n]) {
case numtoken:
printf("%d",exp rdata[++n]);
endcase
case idtoken:
printf("%c",exp rdata[++n]);
endcase
case addtoken: case subtoken: case multoken: case divtoken:
printf("%c",opn ames[exprdata[n]]);
endcase
case leftbtoken:
printf("(");
endcase
case rightbtoken:
printf(")");
endcase
};
++n;
};
puts("");
}

Mar 30 '08 #3

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

Similar topics

303
17764
by: mike420 | last post by:
In the context of LATEX, some Pythonista asked what the big successes of Lisp were. I think there were at least three *big* successes. a. orbitz.com web site uses Lisp for algorithms, etc. b. Yahoo store was originally written in Lisp. c. Emacs The issues with these will probably come up, so I might as well mention them myself (which will also make this a more balanced
2
2180
by: Todd Moyer | last post by:
I would like to use Python to parse a *python-like* data description language. That is, it would have it's own keywords, but would have a syntax like Python. For instance: Ob1 ('A'): Ob2 ('B'): Ob3 ('D') Ob3 ('E') Ob2 ('C')
19
2030
by: Alex Mizrahi | last post by:
Hello, All! i have 3mb long XML document with about 150000 lines (i think it has about 200000 elements there) which i want to parse to DOM to work with. first i thought there will be no problems, but there were.. first i tried Python.. there's special interest group that wants to "make Python become the premier language for XML processing" so i thought there will be no problems with this document.. i used xml.dom.minidom to parse it.....
4
7248
by: Pushya | last post by:
Hello - I am trying to parse a .XSD file to obtain information about element name and type in the file. I have been trying to find some kind of documentation for Schema Parsing. All I come across is documentation for validating XML files against XSD files. Is ther any way to parse the XSD file itself? Any help will be appreciated. Thanks for your time.
16
2906
by: Terry | last post by:
Hi, This is a newbie's question. I want to preload 4 images and only when all 4 images has been loaded into browser's cache, I want to start a slideshow() function. If images are not completed loaded into cache, the slideshow doesn't look very nice. I am not sure how/when to call the slideshow() function to make sure it starts after the preload has been completed.
22
3804
by: Tony Johansson | last post by:
Hello Experts! I'm reading i a book about C++ and they mention infix with telling what it is. I hope you out there can do so. Many thanks! //Tony
5
3261
by: gamehack | last post by:
Hi all, I was thinking about parsing equations but I can't think of any generic approach. Basically I have a struct called math_term which is something like: struct math_term { char sign; int constant; int x; int y;
3
3458
by: Jon Slaughter | last post by:
Is there anything like yacc or spirit for C#? What is the "standard" method for parsing grammars in C#? The last few days I have been looking at boost spirit and really like how it works. What I was hoping for is a library that could take an ABNF grammar and output C# code that represents that grammar. (A tree of classes that contained the syntatic structure of the grammar which) Right now a friend of mine is working on an parser and I...
2
2668
by: nicky123 | last post by:
Hi everyone, This is a brief description that I have provided for parsing & displaying an XML document using DOM API. Please feel free to post your own comments & views regarding this discussion. Thank you. The first step of parsing an XML document is to import the DOM API related classes such as :- java.io.* which contains all the interfaces to perform an I/O operation. org.xml.sax.* which contains all the interfaces...
0
9454
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
10267
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...
0
9915
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
8939
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...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6717
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
5358
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3611
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2852
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.