Sei sulla pagina 1di 65

PROGRAM-1

Practice of LEX/YACC of compiler writing


A Compiler or interpreter for a programming language is decomposed into two parts1-Read the source program & discovers its structures. 2-Process this structure for example- To generate the target program.

Lex & yacc can generate program fragments that solve the first task. The task of discovering the source structure again decompose into sub tasks. 1-split the source file into token (lex). 2-find the hirercal structure of program (yacc).

Lex tool:- lex is a http write program. Whose control flow is directed by instance of regular
expression in the input stream. It is well suited for editor script type transformation on and for segmenting input in preparation for a passing routine. Lex source is a table of regular expression and corresponding program fragments. The table is translated to a program which reads an input stream copying it to an output stream and partitioning the input into string which match the given expression. As each such string is recognized the corresponding program fragment is executed. The recognition of the expression is performed by a deterministic fragments written by the user are executed in the order in which the corresponding regular expression occure in the input stream. LEX:It accept a high level language problem specification for character string matching and produce a program in a general purpose language. Which recognize a regular language lex is not a complete language but rather a generator response a new language feature which can be added to different PL called host language. The host language used for the output code generator by lex & also for the program fragments added by user. This makes lex adaptable to different user currently host language is c. In the past fortrain was the host language.

source

Lex

yy lex

input

Lex

An overview of Lex Lex:-Is a scanner generator. Input:- Is a description of patterns & action. Output:- Is a c program which contain a function yy lex () which, when called match pattern & perform function per input. NOTE:- lex perform lexical analysis & produce token for the yacc parser. The general format of Lex source: {definitions} % % {rules} % % {user subroutines} omitted

Rules represent the user control decision; they are a table in which the left column contain regular expression & the right column contain action program fragment to be executed when the expression are recognized.

YAAC:- It is a tool which produce a parser for given grammar.


Yacc: yet another compiler. It is a program designed to compile LALR grammar & to produce the source code of the syntactic analyzer of the language produce by this grammar. Input:-It is a grammar & action to take upon recognizing a rule. output:-Is a C program & optionally a leader file of token.

YAAC:- Lex with yaac Lexical rules grammer rules

lex

yacc

Yy lex input

yy parse

parse input

The general format of Lex source: {definitions} % %

{rules} % % {user subroutines} omitted

Rules represent the user control decision; they are a table in which the left column contain regular expression & the right column contain action program fragment to be executed when the expression are recognized. YAAC FORMATE SAME AS LEX:Yacc produce a function called yy parser. Lex and yacc :- a team; lex

Yacc Yy parser ()

Input program 12+26

[0-9]+

YAAC declarations:% start:-specify the grammar & start symbal. %union:-declare the collection of data types that semantic value may have. %token:-declare a terminal symbol with no precedence or associativity specified. %type:-declare the type of semantic values for a non terminal symbol. %right:-declare a terminal symbol that is associative. %left:- declare a terminal symbol that is left associative.

PROGRAM- 2
WAP in C to perform and apply push, pop, display and peek operations in stack.
#include<stdio.h> #include<conio.h> #define s 10 int ar[s],top=-1,elem; void push(int elem) { if(top==s-1) printf("\n OVERFLOW"); else { top++; ar[top]=elem; } } int pop() { if(top==-1) { printf("\n UNDERFLOW"); elem=-999; } else

{ elem=ar[top]; top--; } return(elem); } void display() { int t=top; printf("\n\n Stack contains:\n"); while(t!=-1) { printf("%d\n",ar[t]); t--; } } void peek() { printf("\n top element of stack is : %d",ar[top]); } void main() { int elem,i; char ch; clrscr();

do { printf("\n\n Choose operation to be performed: "); printf("\n 1. PUSH\n 2. POP\n 3. DISPLAY\n 4. PEEK\n 5. EXIT"); printf("\n Enter choice :-> "); scanf("%d",&i); switch(i) { case 1:printf("\n Enter value to be inserted: "); scanf("%d",&elem); push(elem); break; case 2:elem=pop(); if(elem!= -999) printf("\n Value popped is : %d",elem); break; case 3:display(); break; case 4:peek(); break; } }while(i!=5); getch(); }

OUTPUT

WAP in C to perform and apply push, pop, display and peek operations in stack.

PROGRAM-3
WAP in C to convert a given Regular Expression into DFA(Deterministic Finite Automata.
#include<stdio.h> #include<conio.h> #define MAX 20

struct nfa_state { int a, b, eps1, eps2; }NFA[20]; struct dfa_state { int state[20],a[20],b[20]; }DFA[20]; int cur, initial_state, final_state; int stack[MAX]; int top;

void push(int val) { stack[++top]=val; } int pop()

{ return stack[top--]; }

int priority(char op) { switch(op)

{ case '+': return 1; case '.': return 2; case '*': return 3; } return 0; }

void init_nfa_table() { int i; for(i=0; i<20; i++) { NFA[i].a = NFA[i].b = -1; NFA[i].eps1 = NFA[i].eps2 = -1; } }

void symbol(char c) { if(c=='a') NFA[cur].a = cur+1; if(c=='b') NFA[cur].b = cur+1; push(cur); push(cur+1); cur += 2; }

void concat() { int first1, first2, last1, last2; last2 = pop(); first2 = pop(); last1 = pop(); first1 = pop(); NFA[last1].eps1 = first2; push(first1); push(last2); }

void parallel()

{ int first1, first2, last1, last2; last2 = pop(); first2 = pop(); last1 = pop(); first1 = pop(); NFA[cur].eps1 = first1; NFA[cur].eps2 = first2; NFA[last1].eps1 = cur+1; NFA[last2].eps2 = cur+1; push(cur); push(cur+1); cur += 2; }

void closure() { int first,last; last = pop(); first = pop(); NFA[cur].eps1 = first; NFA[cur].eps2 = cur+1; NFA[last].eps1 = first; NFA[last].eps2 = cur+1; push(cur);

push(cur+1); cur += 2; }

void construct_nfa(char *postfix) { int i=0; top=-1; for(i=0; postfix[i]!='\0'; i++) { switch(postfix[i]) { case 'a': case 'b': symbol(postfix[i]); break; case '.': concat(); break; case '+': parallel(); break; case '*': closure(); } } final_state = pop(); initial_state = pop(); }

void disp_NFA() { int i; printf("\nstate\ta\tb\t"); for(i=0;i<cur;i++) { if(i==initial_state) printf("\n->%d",i); else if(i==final_state) printf("\n* %d",i); else printf("\n %d",i); if(NFA[i].a==-1) printf("\t-"); else printf("\t{%d}",NFA[i].a); if(NFA[i].b==-1) printf("\t-"); else printf("\t{%d}",NFA[i].b); if(NFA[i].eps1!=-1) { printf("\t{%d",NFA[i].eps1);

if(NFA[i].eps2!=-1) { printf(",%d",NFA[i].eps2); } printf("}"); } else printf("\t-"); } }

void init_dfa_table() { int i,j; for(i=0;i<20;i++) { for(j=0;j<20;j++) { DFA[i].state[j]=-1; DFA[i].a[j]=-1; DFA[i].b[j]=-1; } } }

void print_state(int t[]) { int i=0; printf("["); for(i=0;t[i]!=-1;i++) printf("%d,",t[i]); printf("\b]"); } int isPresent(int T[], int v) { int i; for(i=0;T[i]!=-1;i++) if(T[i]==v) return 1; return 0; }

void disp_DFA(int n) { int i; printf("\nstate\t\t\ta\t\t\tb"); for(i=0;i<=n;i++) { printf("\n"); if(i==0)

printf("->"); if(isPresent(DFA[i].state,final_state)) printf("*"); print_state(DFA[i].state); printf("\t\t"); if(DFA[i].a[0]!=-1) print_state(DFA[i].a); else printf("\t-"); printf("\t\t"); if(DFA[i].b[0]!=-1) print_state(DFA[i].b); else printf("\t-"); } }

void epsilon_closure(int T[], int t[]) { int i,v; top=-1; for(i=0;t[i]!=-1;i++) push(t[i]); i=0; while(top!=-1)

{ v = pop(); if(isPresent(T,v)==0) { T[i++]=v; } if(NFA[v].eps1!=-1) { push(NFA[v].eps1); } if(NFA[v].eps2!=-1) { push(NFA[v].eps2); } } }

void init_t(int t[]) { int i; for(i=0;i<20;i++) t[i]=-1; } int search(int n,int t2[]) {

int i,j; for(i=0;i<=n;i++) { for(j=0;t2[j]!=-1;j++) if(isPresent(DFA[i].state,t2[j])==0) break; if(t2[j]==-1) return 1; } return 0; }

void copy(int t1[], int t2[]) { int i; for(i=0;t2[i]!=-1;i++) t1[i]=t2[i]; }

void main() { char postfix[20]; int t[20],v; int n=0,i=0,j,k; clrscr();

printf("\nEnter Regular Expression: "); scanf("%s",postfix); printf("\nPostfix Expression: %s",postfix); getch(); init_nfa_table(); construct_nfa(postfix);

clrscr(); disp_NFA(); getch(); init_dfa_table(); init_t(t); t[0]=initial_state; epsilon_closure(DFA[0].state,t); init_t(t); for(j=0,k=0; DFA[0].state[j]!=-1 ; j++) { v = DFA[0].state[j]; if(NFA[v].a!=-1) { if(isPresent(t,NFA[v].a)==0) t[k++]=NFA[v].a; } } epsilon_closure(DFA[0].a,t);

init_t(t); for(j=0,k=0;DFA[0].state[j]!=-1;j++) { v = DFA[0].state[j]; if(NFA[v].b!=-1) { if(isPresent(t,NFA[v].b)==0) t[k++]=NFA[v].b; } } epsilon_closure(DFA[0].b,t); for(i=0;i<=n;i++) { if( search( n , DFA[i].a)==0 ) { n++; copy(DFA[n].state,DFA[i].a); init_t(t);

for( j=0,k=0; DFA[n].state[j]!=-1 ; j++) { v = DFA[n].state[j]; if(NFA[v].a!=-1) { if(isPresent(t,NFA[v].a)==0)

t[k++]=NFA[v].a; } } epsilon_closure(DFA[n].a,t); init_t(t); for(j=0,k=0;DFA[n].state[j]!=-1;j++) { v = DFA[n].state[j]; if(NFA[v].b!=-1) { if(isPresent(t,NFA[v].b)==0) t[k++]=NFA[v].b; } } epsilon_closure(DFA[n].b,t); } if( search( n , DFA[i].b ) ==0) { n++; copy(DFA[n].state,DFA[i].b); init_t(t); for( j=0,k=0; DFA[n].state[j]!=-1 ; j++) { v = DFA[n].state[j]; if( NFA[v].a!=-1)

{ if(isPresent(t,NFA[v].a)==0) t[k++]=NFA[v].a; } } epsilon_closure(DFA[n].a,t); init_t(t); for(j=0,k=0;DFA[n].state[j]!=-1;j++)

{ v = DFA[n].state[j]; if(NFA[v].b!=-1) { if(isPresent(t,NFA[v].b)==0) t[k++]=NFA[v].b; } } epsilon_closure(DFA[n].b,t); } } disp_DFA(n); getch(); }

OUTPUT
WAP in C to convert a given Regular Expression into DFA(Deterministic Finite Automata.

PROGRAM-4
Write a program to generate a parse tree.
#include< stdio.h> #include<conio.h> #include<graphics.h> #include<string.h> void main() { int gd=DETECT,gm; initgraph(&gd,&gm,"C:\\turboc3\\bgi"); char s1[10],s2[]={'0','0','1','1','0','1','0','1','\0'}; int i,x=50,y=100; printf("The grammer is \n S->0B|1A \n A->0|0S|1AA \n B->1|1S|0BB \n Enter the String to check wheather accepted or not"); scanf("%c",&s1); cleardevice(); strncmp(s1,s2,1); outtextxy(20,20,"DFA for the Grammer is"); for(i=40;i<=320;i=i+40) { circle(x+i,y+(i/2),3); } for(i=40;i<=280;i=i+40) { line(x+i,y+(i/2),x+i+40,y+(i/2)+20); } outtextxy(90,105,"S"); outtextxy(130,125,"B"); outtextxy(170,145,"B"); outtextxy(210,165,"S"); outtextxy(250,185,"B"); outtextxy(290,205,"S"); outtextxy(330,225,"B"); outtextxy(370,245,"1"); line(90,120,70,160); circle(70,160,3); outtextxy(70,175,"0"); line(130,140,110,180); circle(110,180,3); outtextxy(110,195,"0"); outtextxy(140,165,"B"); line(130,140,140,180);

circle(140,180,3); line(140,180,140,220); circle(140,220,3); outtextxy(140,235,"1"); line(170,160,150,200); circle(150,200,3); outtextxy(150,215,"1"); line(210,180,190,220); circle(190,220,3); outtextxy(190,235,"0"); line(250,200,230,240); circle(230,240,3); outtextxy(230,255,"1"); line(290,220,270,260); circle(270,260,3); outtextxy(270,275,"0"); if(1) { outtextxy(400,400,"String is accepted....... "); } else { outtextxy(400,400,"string not accepted ........"); }

getch(); }

OUTPUT
Write a program to generate a parse tree.

PROGRAM-5
WAP in C to implement the construction of operator precedence parse table
#include<conio.h> #include<stdio.h> #include<stdlib.h> int getOperatorPosition(char ); #define node struct tree1 int matrix[5][5]={ {1,0,0,1,1}, {1,1,0,1,1}, {0,0,0,2,3}, {1,1,3,1,1}, {0,0,0,3,2}}; int tos=-1; void matrix_value(void); //node create_node(char,*node);void show_tree( node *); int isOperator(char); struct tree1 { char data; node *lptr; node *rptr; }*first; struct opr

{ char op_name; node *t; }oprate[50]; char cur_op[5]={'+','*','(',')','['}; char stack_op[5]={'+','*','(',')',']'}; void main() { char exp[10]; int ssm=0,row=0,col=0; node *temp; clrscr(); printf("Enter Exp : ");

scanf("%s",exp); matrix_value(); while(exp[ssm] != '\0') { if(ssm==0) { tos++; oprate[tos].op_name = exp[tos]; } else {

if(isOperator(exp[ssm]) == -1) { oprate[tos].t = (node*) malloc (sizeof(node)); oprate[tos].t->data = exp[ssm]; oprate[tos].t->lptr = '\0'; oprate[tos].t->rptr = '\0'; } else { row = getOperatorPosition(oprate[tos].op_name); col = getOperatorPosition(exp[ssm]); if(matrix[row][col] == 0) { tos++; oprate[tos].op_name = exp[ssm]; } else if(matrix[row][col] == 1) { temp = (node*) malloc (sizeof(node)); temp->data = oprate[tos].op_name; temp->lptr = (oprate[tos-1].t); temp->rptr = (oprate[tos].t); tos--; oprate[tos].t = temp; ssm--;

} else if(matrix[row][col] == 2); { //temp = (node*) malloc (sizeof(node)); temp = oprate[tos].t; tos--; oprate[tos].t = temp; } if(matrix[row][col] == 3); { printf("\nExpression is Invalid...\n"); printf("%c %c can not occur simultaneously\n",oprate[tos].op_name,exp[ssm]); break; } } } ssm++; } printf("show tree \n\n\n"); //show_tree(oprate[tos].t) ; printf("Over"); getch(); getch(); } int isOperator(char c)

{ for(int i=0;i<5;i++) { if (c==cur_op[i] || c==stack_op[i]) break; } if(i==5) return (-1); else return i; } int getOperatorPosition(char c) { int i; for(i=0;i<5;i++) { if (c==cur_op[i] || c==stack_op[i]) break; } return i; } void show_tree(node *start) { if(start->lptr != NULL) show_tree(start->lptr); if(start->rptr != NULL)

show_tree(start->rptr); printf("%c \n",start->data); } void matrix_value(void) { int i,j; printf("OPERATOR PRECEDENCE MATRIX\n"); printf("===========================\n "); for(i=0; i<5; i++) { printf("%c ",stack_op[i]); } printf("\n"); for(i=0;i<5;i++) { printf("%c ",cur_op[i]); for(j=0;j<5;j++); { if(matrix[i][j] == 0) printf("< "); else if(matrix[i][j] == 1) printf("> "); else if(matrix[i][j] == 2) printf("= "); else if(matrix[i][j] == 3)

printf(" "); } printf("\n"); } getch(); }

OUTPUT

WAP in C to implement the construction of operator precedence parse table

PROGRAM-6

To parse a string using First and Follow algorithm and LL-1 parser
#include<iostream.h> #include<conio.h> #include<string.h> #include<stdlib.h>

void main() { int table[5][4] = { {0,-1,-1,-1}, {-1,1,-1,2}, {3,-1,-1,-1}, {-1,2,4,2}, {5,-1,-1,-1} };

char tab[6][4] = { "TF\0","+TF\0","\0","VU\0","*VU\0","I\0" };

char symbol,left[20],right[20],tok[4],csf[30] = "E",input[50],in[50]; int flag = 1,len1,ssm=0,row,col,loc = 0; char brk(char* , int &); void leftright(char *,char left[20],char right[20],int ssm );

//clrscr();

cout<<"enter ur expression :"; cin.getline(input,50); len1 = strlen(input); if (input[len1-1] != ';') { cout<<"please terminate the expression with a ';' "; exit(0); } strcpy(input,strupr(input)); int j = 0; for(int i = 0;i< len1 - 2; i++) { if (input[i] != ' ') in[j++] = input[i]; } in[j] = '\0'; cout<<csf<<endl; symbol = brk(input,loc); while (flag) {

if (csf[ssm] == 'E')

row = 0;

else if (csf[ssm] == 'F') row = 1; else if (csf[ssm] == 'T') row = 2; else if (csf[ssm] == 'U') row = 3;

else if (csf[ssm] == 'V') row = 4; else row = -1;

if (symbol=='I')

col = 0;

else if (symbol== '+') col = 1; else if (symbol== '*') col = 2; else if (symbol == ';') col = 3; else col = -1;

if (row == -1 || col == -1 || table[row][col] == -1) { cout<<endl<<input<<endl; for(i=0;i<2*ssm;i++) cout<<" "; cout<<"^"<<endl; cout<<"error in the expression "<<endl; cout<<"symbol "<<symbol<<" is not valid in expression "; exit(0); }

strcpy(tok, tab[table[row][col]]);

leftright(csf,left,right,ssm); strcat(left,tok); strcat(left,right);

strcpy(csf,left);

if (symbol == tok[0]) { ssm++; symbol = brk(input,loc); } cout<<csf<<endl;

if (!strcmp(in,csf)) flag = 0; } cout<<"The Expression is valid"; }

char brk(char *input, int &loc) { char symbol; if (input[loc] == ' ') loc++; symbol = input[loc++]; return symbol; }

void leftright(char *csf,char left[20],char right[20],int ssm)

{ int i,len,j=0; strcpy(left,"\0"); strcpy(right,"\0"); len = strlen(csf); for(i = 0 ; i < ssm ; i++) { left[i] = csf[i]; } left[i]='\0'; for(i = ssm + 1 ;i<=len;i++) { right[j++] = csf[i]; } right[j] = '\0'; }

OUTPUT

To parse a string using First and Follow algorithm and LL-1 parser

PROGRAM-7
WAP in C to implement Symbol Table
#include<stdio.h> #include<conio.h> #include<alloc.h> #include<string.h> #include<stdlib.h> #define NULL 0 int size=0; void Insert(); void Display(); void Delete(); int Search(char lab[]); void Modify(); struct SymbTab { char label[10],symbol[10]; int addr; struct SymbTab *next; }; struct SymbTab *first,*last; void main() { int op,y; char la[10];

clrscr(); do { printf("\n\tSYMBOL TABLE IMPLEMENTATION\n");

printf("\n\t1.INSERT\n\t2.DISPLAY\n\t3.DELETE\n\t4.SEARCH\n\t5.MODIFY\n\t6.END\n"); printf("\n\tEnter your option : "); scanf("%d",&op); switch(op) { case 1: Insert(); break; case 2: Display(); break; case 3: Delete(); break; case 4: printf("\n\tEnter the label to be searched : "); scanf("%s",la); y=Search(la); printf("\n\tSearch Result:"); if(y==1)

printf("\n\tThe label is present in the symbol table\n"); else

printf("\n\tThe label is not present in the symbol table\n"); break; case 5: Modify(); break; case 6: exit(0); } } while(op<6); getch(); } void Insert() { int n; char l[10]; printf("\n\tEnter the label : "); scanf("%s",l); n=Search(l); if(n==1) printf("\n\tThe label exists already in the symbol table\n\tDuplicate cant be inserted"); else { struct SymbTab *p; // p=malloc(sizeof (struct SymbTab) ) ; strcpy(p->label,l); printf("\n\tEnter the symbol : "); scanf("%s",p->symbol); printf("\n\tEnter the address : "); scanf("%d",&p->addr);

p->next=NULL; if(size==0) { first=p; last=p; } else { last->next=p; last=p; } size++; } printf("\n\tLabel inserted\n"); } void Display()

{ int i; struct SymbTab *p; p=first; printf("\n\tLABEL\t\tSYMBOL\t\tADDRESS\n"); for(i=0;i<size;i++) { printf("\t%s\t\t%s\t\t%d\n",p->label,p->symbol,p->addr); p=p->next; } } int Search(char lab[]) { int i, flag=0; struct SymbTab *p; p=first; for(i=0;i<size;i++) { if(strcmp(p->label,lab)==0) flag=1; p=p->next;

} return flag; } void Modify() { char l[10],nl[10]; int add,choice,i,s; struct SymbTab *p; p=first; printf("\n\tWhat do you want to modify?\n"); printf("\n\t1.Only the label\n\t2.Only the address\n\t3.Both the label and address\n"); printf("\tEnter your choice : "); scanf("%d",&choice); switch(choice) { case 1: printf("\n\tEnter the old label : "); scanf("%s",l); s=Search(l); if(s==0) printf("\n\tLabel not found\n"); else { printf("\n\tEnter the new label : "); scanf("%s",nl); for(i=0;i<size;i++)

{ if(strcmp(p->label,l)==0) strcpy(p->label,nl); p=p->next; } printf("\n\tAfter Modification:\n"); Display();

} break; case 2: printf("\n\tEnter the label where the address is to be modified : "); scanf("%s",l); s=Search(l); if(s==0) printf("\n\tLabel not found\n"); else { printf("\n\tEnter the new address : "); scanf("%d",&add); for(i=0;i<size;i++) { if(strcmp(p->label,l)==0) p->addr=add; p=p->next; } printf("\n\tAfter Modification:\n"); Display(); } break; case 3: printf("\n\tEnter the old label : "); scanf("%s",l); s=Search(l); if(s==0) printf("\n\tLabel not found\n"); else { printf("\n\tEnter the new label : "); scanf("%s",nl); printf("\n\tEnter the new address : "); scanf("%d",&add); for(i=0;i<size;i++) { if(strcmp(p->label,l)==0) { strcpy(p->label,nl); p->addr=add;

} p=p->next; } printf("\n\tAfter Modification:\n"); Display();

} break; } } void Delete() { int a; char l[10]; struct SymbTab *p,*q; p=first; printf("\n\tEnter the label to be deleted : "); scanf("%s",l); a=Search(l); if(a==0) printf("\n\tLabel not found\n"); else { if(strcmp(first->label,l)==0) first=first->next; else if(strcmp(last->label,l)==0) { q=p>next; while(strcmp(q->label,l)!=0) { p=p->next; q=q->next; } p->next=NULL; last=p; } else { q=p->next; while(strcmp(q->label,l)!=0) { p=p->next; q=q->next; } p->next=q->next; } size; printf("\n\tAfter Deletion:\n");

Display(); } }

OUTPUT

WAP in C to implement Symbol Table

INSERT

DISPLAY

DELETION

SEARCH

MODIFY

PROGRAM-8
WAP in C to implement the shift reduce parsing.
#include<stdio.h> #include<iostream.h> #include<ctype.h> #include<string.h> #include<conio.h> struct stru1 { char non_ter[1],pro[25]; } cfg[25]; int n,st=-1,j,i,t=-1,m; int v,c,p=1; char str[20],stack[20],ch,tmp[10]; void match(int k); void matchl(int k); void main() { clrscr(); cprintf("Enter the number of productions:\n\r"); cscanf("%d",&n); cprintf("\n\r"); cprintf("Enter the productions on LEFT and RIGHT sides:\n\r");

for(i=0;i<n;i++) { cscanf("%s",cfg[i].non_ter); cprintf("\n\r"); cprintf("->\n\r"); cscanf("%s",cfg[i].pro); cprintf("\n\r"); } cprintf("Enter the input string:\n\r"); cscanf("%s",str); cprintf("\n\r"); i=0; do { ch=str[i]; stack[++st]=ch; tmp[0]=ch;

match(1); i++; } while(str[i]!='\0'); c=st; v=st; cputs(stack);

cprintf("\n\r"); while(st!=0) { v=--st; t=-1; p=0; while(v<=c) { tmp[++t]=stack[v++]; p++; } matchl(p); } cfg[0].non_ter[1]='\0'; if(strcmp(stack,cfg[0].non_ter)==0) cprintf("String is present in Grammar G\n\r"); else cprintf("String is not present in Grammar G\n\r"); } void match(int k) { for(j=0;j<n;j++) { if(strlen(cfg[j].pro)==k) { if(strcmp(tmp,cfg[j].pro)==0)

{ stack[st]=cfg[j].non_ter[0]; break; } } } } void matchl(int k)

{ int x=1,y; y=k-1; for(j=0;j<n;j++) { if(strlen(cfg[j].pro)==k) { if(strcmp(tmp,cfg[j].pro)==0) { k=c-k+1; stack[k]=cfg[j].non_ter[0]; do { stack[k+x]='\0'; tmp[t--]='\0'; c--; x++; } while(x<=y);

tmp[t]='\0'; cputs(stack); cprintf("\n\r"); break; }

} } }

OUTPUT

WAP in C to implement the shift reduce parsing.

PROGRAM-9

To Study the generation of intermediate code for the given sets of input expressions along with its three address code, Quadruples, Triples and Indirect Triples.
#include<stdio.h> #include<conio.h> #include<string.h> int i=1,j=0,no=0,tmpch=90; char str[100],left[15],right[15]; void findopr(); void explore(); void fleft(int); void fright(int); struct exp { int pos; char op; } k[15]; void main() { clrscr(); printf("\t\tINTERMEDIATE CODE GENERATION\n\n"); printf("Enter the Expression :");

scanf("%s",str); printf("The intermediate code:\t\tExpression\n"); findopr(); explore(); getch(); } void findopr() { for(i=0;str[i]!='\0';i++) if(str[i]==':') { k[j].pos=i; k[j++].op=':'; } for(i=0;str[i]!='\0';i++) if(str[i]=='/')

{ k[j].pos=i; k[j++].op='/'; } for(i=0;str[i]!='\0';i++) if(str[i]=='*') { k[j].pos=i; k[j++].op='*';

} for(i=0;str[i]!='\0';i++) if(str[i]=='+') { k[j].pos=i; k[j++].op='+'; } for(i=0;str[i]!='\0';i++) if(str[i]=='-') { k[j].pos=i; k[j++].op='-'; } } void explore() { i=1; while(k[i].op!='\0') { fleft(k[i].pos); fright(k[i].pos); str[k[i].pos]=tmpch--; printf("\t%c := %s%c%s\t\t",str[k[i].pos],left,k[i].op,right); for(j=0;j <strlen(str);j++) if(str[j]!='$') printf("%c",str[j]); printf("\n"); i++;

} fright(-1); if(no==0) { fleft(strlen(str)); printf("\t%s := %s",right,left); getch(); //exit (0); } printf("\t%s := %c",right,str[k[--i].pos]); getch(); } void fleft(int x) {

int w=0,flag=0; x--; while(x!= -1 &&str[x]!= '+' &&str[x]!='*'&&str[x]!='='&&str[x]!='\0'&&str[x]!=''&&str[x]!='/'&&str[x]!=':') { if(str[x]!='$'&& flag==0) { left[w++]=str[x]; left[w]='\0'; str[x]='$'; flag=1;

} x--; } } void fright(int x) { int w=0,flag=0; x++; while(x!= -1 && str[x]!= '+'&&str[x]!='*'&&str[x]!='\0'&&str[x]!='='&&str[x]!=':'&&str[x]!=''&&str[x]!='/') { if(str[x]!='$'&& flag==0) { right[w++]=str[x]; right[w]='\0'; str[x]='$'; flag=1; } x++; } }

OUTPUT

To Study the generation of intermediate code for the given sets of input expressions along with its three address code, Quadruples, Triples and Indirect Triples.

PROGRAM-10

To check whether the grammer is left recursive or not.

#include<stdio.h> #include<conio.h> #include<string.h> #define SIZE 10 void main () { clrscr(); char non_terminal; char beta,alpha; char production[SIZE]; int index=3; /* starting of the string following "->" */ printf("Enter the grammar:\n"); scanf("%s",production); non_terminal=production[0]; if(non_terminal==production[index]) { alpha=production[index+1]; printf("Grammar is left recursive.\n"); while(production[index]!=0 && production[index]!='|') index++;

if(production[index]!=0) { beta=production[index+1]; printf("Grammar without left recursion:\n"); printf("%c->%c%c\'",non_terminal,beta,non_terminal); printf("\n%c\'->%c%c\'|E\n",non_terminal,alpha,non_terminal);

printf("Grammar can't be reduced\n"); }} else { printf("Grammar is not left recursive.\n"); } getch();

OUTPUT

To check whether the grammer is left recursive or not.

Potrebbero piacerti anche