nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN...

53
Exp.No. : 1 IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include<stdio.h> #include<conio.h> //#include<graphics.h> #include<string.h> struct str { char a[30]; }s; void main() { FILE *fp; int j,f=0,flag,gd,gm; char p[15][15]={"stdio.h","include","main","math.h","string.h", "graphics.h","void","int","float","char"}; char q[15] [15]={"(",")","[","]","{","}",":",".","#",";",",","?"}; char r[15][15]={"+","-","*","/","<",">","%","="}; gd=DETECT; initgraph(&gd,&gm,""); gotoxy(28,2); printf("Token Seperation"); rectangle(3,35,530,475); rectangle(3,35,100,475); rectangle(200,35,300,475); rectangle(300,35,400,475); rectangle(3,35,530,75); gotoxy(3,4); printf("KEYWORDS"); gotoxy(16,4); printf("PUNCT.SYMS"); gotoxy(28,4); printf("OPERATORS"); gotoxy(40,4); printf("CONSTANTS"); 1

Transcript of nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN...

Page 1: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

Exp.No. : 1IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION)

#include<stdio.h>#include<conio.h>//#include<graphics.h>#include<string.h>struct str{

char a[30];}s;

void main(){

FILE *fp;int j,f=0,flag,gd,gm;char p[15][15]={"stdio.h","include","main","math.h","string.h",

"graphics.h","void","int","float","char"};char q[15][15]={"(",")","[","]","{","}",":",".","#",";",",","?"};char r[15][15]={"+","-","*","/","<",">","%","="};gd=DETECT;initgraph(&gd,&gm,"");gotoxy(28,2);printf("Token Seperation");rectangle(3,35,530,475);rectangle(3,35,100,475);rectangle(200,35,300,475);rectangle(300,35,400,475);rectangle(3,35,530,75);gotoxy(3,4);printf("KEYWORDS");gotoxy(16,4);printf("PUNCT.SYMS");gotoxy(28,4);printf("OPERATORS");gotoxy(40,4);printf("CONSTANTS");gotoxy(53,4);printf("IDENTIFIERS");fp=fopen("add.txt","r");f=7;do{

fscanf(fp,"%s",s.a);for(j=0;j<=15;j++)

1

Page 2: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

{if(strcmp(s.a,p[j])==0)flag=0;

}for(j=0;j<=15;j++){

if(strcmp(s.a,q[j])==0)flag=1;

}for(j=0;j<=15;j++){

if(strcmp(s.a,r[j])==0)flag=2;

}if(atoi(s.a)>0||atoi(s.a)<0)flag=3;printf("\n");switch(flag){

case 0:gotoxy(5,f);printf("%s",s.a);break;

case 1:gotoxy(17,f);printf("%s",s.a);break;

case 2:gotoxy(29,f);printf("%s",s.a);break;

case 3:gotoxy(41,f);printf("%s",s.a);break;

default:gotoxy(53,f);printf("%s",s.a);

}f++;flag=-1;

}while(!feof(fp));getch();closegraph();

}

2

Page 3: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

Input File: add.

void main ( ){

int x = 6;int y = 4;x = x + y;

}

Exp.No.2://Implementation of lexical analyzer using c

#include<stdio.h>#include<conio.h>#include<string.h>#define size 128#define NONE -1#define EOS '\0'#define NUM 256#define keyword 257#define punt 258#define id 259#define assign 260#define arith 200#define rel_op 261#define DONE 262#define MAX 999char buffer[size],lexemes[MAX];int lastchar=-1,lastentry=0,tokenval=NONE,lineno=1;struct entry{

char *lexptr;int token;

}symtable[100];struct entry keywords[]={"if",keyword,"else",keyword,"for",keyword,"int",keyword,"float",

keyword,"double",keyword,"struct",keyword,"return",keyword,0,0};int look_up(char s[]){

int k;for(k=lastentry;k>0;k=k-1)

if(strcmp(symtable[k].lexptr,s)==0)return k;

return 0;}int insert(char s[],int tok)

3

Page 4: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

{int len;len=strlen(s);lastentry=lastentry+1;symtable[lastentry].token=tok;symtable[lastentry].lexptr=&lexemes[lastchar+1];lastchar=lastchar+len+1;strcpy(symtable[lastentry].lexptr,s);return lastentry;

}void initialize(){

struct entry *ptr;for(ptr=keywords;ptr->token;ptr++)insert(ptr->lexptr,ptr->token);

}int lexer(){

int t,val,i=0;while(1){

t=getchar();if(t==' '||t=='\t')

;else if(t=='\n')

lineno=lineno+1;else if(t=='('||t==')'||t==','||t==';'||t=='{'||t=='}')

return punt;else if(t=='<'||t=='>')

return rel_op;else if(t=='+'||t=='-'||t=='*'||t=='/')

return arith;else if(t=='=')

return assign;else if(isdigit(t)){

ungetc(t,stdin);scanf("%d",&tokenval);return NUM;

}else if(isalpha(t)){

while(isalnum(t)){

buffer[i]=t;t=getchar();

4

Page 5: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

i=i+1;}buffer[i]=EOS;if(t!=EOF)

ungetc(t,stdin);val=look_up(buffer);if(val==0)

val=insert(buffer,id);tokenval=val;return symtable[val].token;

}else if(t==EOF)

return DONE;else{

tokenval=NONE;return t;

}}

}void main(){

int lookahead;char ans;clrscr();initialize();printf("\n Enter the expression \n Press ctrl z to terminate...\n");lookahead=lexer();while(lookahead!=DONE){

if(lookahead==NUM)printf("\n Number:%d",tokenval);

if(lookahead==arith)printf("\n Arithmetic Operator");

if(lookahead==punt)printf("\n Punctuation Symbol");

if(lookahead==id)printf("\n Identifier:%s",symtable[tokenval].lexptr);

if(lookahead==keyword)printf("\n Keyword");

if(lookahead==assign)printf("\n Assignment operator");

if(lookahead==rel_op)printf("\n Relational operator");

lookahead=lexer();}

5

Page 6: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

}

Exp.No.3Implementation of lexical analyzer using LEX

%{#include<stdio.h>%}%%[0-9]+ {printf("\n %s is a number \n",yytext);}int |float |long |double |case |switch |break |if |else |exit |continue |struct |const |atof |

6

Page 7: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

atoi |typedef |return |printf |scanf |void {printf("\n %s is the keyword \n",yytext);}[a-zA-Z][a-zA-Z0-9]* {printf("\n %s is an identifier \n",yytext);}= {printf("\n %s is an assignment operator\n",yytext);}\>= |\> |\< |== {printf("\n %s is a relational operator\n",yytext);}\+ |\- |\* |\/ {printf("\n %s is an arithmetic operator\n",yytext);}; |"(" |")" |"{" |"}" {printf("\n %s is a symbol\n",yytext);}"/*" {printf("\n %s is a comment line\n",yytext);}%%int main(int argc,char **argv){ if(argc>1) { FILE *file; file=fopen(argv[1],"r"); if(!file) { printf("Could not open %s",argv[1]); exit(0); } yyin=file; } yylex(); printf("\n\n"); return 0;}

4. a. Program to recognize a valid arithmetic expression

7

Page 8: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

AIM:     

       To write a Yacc program to valid arithmetic expression using Yacc .

ALGORITHM:

Step1:  Start the program.

Step2:  Reading an expression .

Step3:  Checking the validating of the given expression according to the rule using yacc.

Step4:  Using expression rule print the result of the given valuesStep5:  Stop the program.

PROGRAM:

//Program to recognize a valid arithmetic expression that uses operator +, -, * and /

LEX PART:%{ #include "y.tab.h"%}%%[a-zA-Z_][a-zA-Z_0-9]* return id;[0-9]+(\.[0-9]*)?      return num;[+/*]                  return op;  .                 return yytext[0];\n                     return 0;%%int yywrap(){return 1;}

YACC PART:

8

Page 9: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

%{ #include<stdio.h>  int valid=1;   %}%token num id op%%start : id '=' s ';'s :     id x            | num x            | '-' num x       | '(' s ')' x     ;x :     op s            | '-' s          |                  ;%%int yyerror(){valid=0; printf("\nInvalid expression!\n");  return 0;}int main(){ printf("\nEnter the expression:\n"); yyparse();if(valid){      printf("\nValid expression!\n");    }}

b. Program to recognize a valid Identifier which start with a letter followed by any number of letter or Digits

AIM :         To write a yacc program to check valid variable followed by letter or digits

ALGORITHM:

9

Page 10: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

Step1: Start the program

Step2: Reading an expression

Step3: Checking the validating of the given expression according to the rule using yacc. 

Step4: Using expression rule print the result of the given values

Step5: Stop the program

PROGRAM CODE:

//Program to recognize a valid variable

LEX PART:%{    #include "y.tab.h"%}%%[a-zA-Z_][a-zA-Z_0-9]* return letter;[0-9]                       return digit;.                      return yytext[0];\n                     return 0;%%int yywrap(){return 1;}

YACC PART:%{ #include<stdio.h>  int valid=1;

10

Page 11: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

%}%token digit letter%%start : letter ss :     letter s  | digit s  |;%%int yyerror(){ printf("\nIts not a identifier!\n"); valid=0;return 0;}int main(){ printf("\nEnter a name to tested for identifier "); yyparse();  if(valid){

  printf("\nIt is a identifier!\n");}}

c. IMPLEMENTATION OF DESKTOP CALCULATOR USING YACC AND LEX

LEX Program

IMPLEMENTATION OF CALCULATOR USING LEX & YACC

April 10, 2018

11

Page 12: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

AIM:

 To write a program for implementing a calculator for computing the given expression using semantic rules of the YACC tool and LEX.

ALGORITHM:

Step1: A Yacc source program has three parts as follows:

       Declarations %%  translation rules %%  supporting C routines

Step2: Declarations Section: This section contains entries that:

 i. Include standard I/O header file.

 ii. Define global variables.

 iii. Define the list rule as the place to start processing.

 iv. Define the tokens used by the parser. v. Define the operators and their precedence.

Step3:  Rules Section: The rules section defines the rules that parse the input stream. Each rule of a grammar production and the associated semantic action.

Step4:  Programs Section: The programs section contains the following subroutines. Because these subroutines are included in this file, it is not necessary to use the yacc library when processing this file.

Step5:  Main- The required main program that calls the yyparse subroutine to start the program.

Step6:  yyerror(s) -This error-handling subroutine only prints a syntax error message.

12

Page 13: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

Step7:  yywrap -The wrap-up subroutine that returns a value of 1 when the end of input occurs. The calc.lex file contains include statements for standard input and output, as programmar file information if we use the -d flag with the yacc command. The y.tab.h file contains definitions for the tokens that the parser program uses.                                                 

Step8: calc.lex contains the rules to generate these tokens from the input stream.

PROGRAM CODE:

//Implementation of calculator using LEX and YACC

LEX PART:

%{#include<stdio.h>#include "y.tab.h"extern int yylval;%}%%[0-9]+ {

          yylval=atoi(yytext);          return NUMBER;       }[\t] ;[\n] return 0;. return yytext[0];%%int yywrap(){return 1;

13

Page 14: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

}

YACC PART:%{ #include<stdio.h>int flag=0;%}%token NUMBER%left '+' '-'%left '*' '/' '%'%left '(' ')'%%ArithmeticExpression: E{ printf("\nResult=%d\n",$$);       return 0;        };E:E'+'E {$$=$1+$3;} |E'-'E {$$=$1-$3;} |E'*'E {$$=$1*$3;} |E'/'E {$$=$1/$3;}|E'%'E {$$=$1%$3;} |'('E')' {$$=$2;} | NUMBER {$$=$1;};%%void main(){printf("\nEnter Any Arithmetic Expression which can have operations Addition, Subtraction, Multiplication, Divison, Modulus and Round brackets:\n");yyparse(); if(flag==0)printf("\nEntered arithmetic expression is Valid\n\n");}

14

Page 15: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

void yyerror(){printf("\nEntered arithmetic expression is Invalid\n\n");flag=1;}

Exp.No.5 CONVERT THE BNF RULES INTO YACC FORM AND WRITE CODE TO GENERATE ABSTRACT SYNTAX TREE USING AND YACC.AIM:To write a program to convert the BNF rules into YACC

BNF-Backus Naur form is formal notationfor encoding grammars intended for humanConsumption. Many programming languages, protocol or formats have BNF description intheir Specification.

ALGORITHM:1. Start the program.2. Declare the declarations as a header file.{include<ctype.h>}3. Token digit4. Define the translations rule like line,expr,term,factor.Line:exp”\n”{print”\n%d\n”,$1)}Expr:expr”+”term($$=$1=$3}Term:term”+”factor($$=$1*$3}FactorFactor”enter”),{$$=$2)%%5. Define the supporting C routines.6. Execute and verify it.7. Stop the program.

PROGRAM: (CONVERT THE BNF RULES INTO YACC)<int.l>

15

Page 16: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

%{

#include"y.tab.h"

#include<stdio.h>

#include<string.h>

int LineNo=1;

%}

identifier [a-zA-Z][_a-zA-Z0-9]*

number [0-9]+|([0-9]*\.[0-9]+)

%%

main\(\) return MAIN;

if return IF;

else return ELSE;

while return WHILE;

int |

char |

float return TYPE;

{identifier} {strcpy(yylval.var,yytext);

return VAR;}

{number} {strcpy(yylval.var,yytext);

return NUM;}

\< |

\> |

\>= |

\<= |

== {strcpy(yylval.var,yytext);

return RELOP;}

[ \t] ;

\n LineNo++;

. return yytext[0];

%%

<int.y>

16

Page 17: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

%{#include<string.h>#include<stdio.h>struct quad{char op[5];char arg1[10];char arg2[10];char result[10];}QUAD[30];struct stack{int items[100];int top;}stk;int Index=0,tIndex=0,StNo,Ind,tInd;extern int LineNo;%}%union{char var[10];}%token <var> NUM VAR RELOP%token MAIN IF ELSE WHILE TYPE%type <var> EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP%left '-' '+'%left '*' '/'%%PROGRAM : MAIN BLOCK;BLOCK: '{' CODE '}';CODE: BLOCK| STATEMENT CODE| STATEMENT;STATEMENT: DESCT ';'| ASSIGNMENT ';'| CONDST| WHILEST;DESCT: TYPE VARLIST;VARLIST: VAR ',' VARLIST| VAR

17

Page 18: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

;ASSIGNMENT: VAR '=' EXPR{strcpy(QUAD[Index].op,"=");strcpy(QUAD[Index].arg1,$3);strcpy(QUAD[Index].arg2,"");strcpy(QUAD[Index].result,$1);strcpy($$,QUAD[Index++].result);};EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);}| EXPR '-' EXPR {AddQuadruple("-",$1,$3,$$);}| EXPR '*' EXPR { AddQuadruple("*",$1,$3,$$);}| EXPR '/' EXPR { AddQuadruple("/",$1,$3,$$);}| '-' EXPR { AddQuadruple("UMIN",$2,"",$$);}| '(' EXPR ')' {strcpy($$,$2);}| VAR| NUM;CONDST: IFST{Ind=pop();sprintf(QUAD[Ind].result,"%d",Index);Ind=pop();sprintf(QUAD[Ind].result,"%d",Index);}| IFST ELSEST;IFST: IF '(' CONDITION ')' {strcpy(QUAD[Index].op,"==");strcpy(QUAD[Index].arg1,$3);strcpy(QUAD[Index].arg2,"FALSE");strcpy(QUAD[Index].result,"- 1");push(Index);Index++;}BLOCK {strcpy(QUAD[Index].op,"GOTO");strcpy(QUAD[Index].arg1,"");strcpy(QUAD[Index].arg2,"");strcpy(QUAD[Index].result,"- 1");push(Index);Index++;};ELSEST: ELSE{tInd=pop();Ind=pop();push(tInd);

18

Page 19: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

sprintf(QUAD[Ind].result,"%d",Index);}BLOCK{Ind=pop();sprintf(QUAD[Ind].result,"%d",Index);};CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$);StNo=Index- 1;}| VAR| NUM;WHILEST: WHILELOOP{Ind=pop();sprintf(QUAD[Ind].result,"%d",StNo);Ind=pop();sprintf(QUAD[Ind].result,"%d",Index);};WHILELOOP: WHILE '(' CONDITION ')' {strcpy(QUAD[Index].op,"==");strcpy(QUAD[Index].arg1,$3);strcpy(QUAD[Index].arg2,"FALSE");strcpy(QUAD[Index].result,"- 1");push(Index);Index++;}BLOCK {strcpy(QUAD[Index].op,"GOTO");strcpy(QUAD[Index].arg1,"");strcpy(QUAD[Index].arg2,"");strcpy(QUAD[Index].result,"- 1");push(Index);Index++;};%%extern FILE *yyin;int main(int argc,char *argv[]){FILE *fp;int i;if(argc>1){fp=fopen(argv[1],"r");if(!fp)

19

Page 20: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

{printf("\n File not found");exit(0);}yyin=fp;}yyparse();printf("\n\n\t\t ----------------------------""\n\t\tPos Operator Arg1 Arg2 Result" "\n\t\t --------------------");for(i=0;i<Index;i++){printf("\n\t\t %d\t %s\t %s\t %s\t%s",i,QUAD[i].op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i].result);}printf("\n\t\t -----------------------");printf("\n\n");return 0;}void push(int data){stk.top++;if(stk.top==100){printf("\n Stack overflow\n");exit(0);}stk.items[stk.top]=data;}int pop(){int data;if(stk.top==- 1){printf("\n Stack underflow\n");exit(0);}data=stk.items[stk.top--];return data;}void AddQuadruple(char op[5],char arg1[10],char arg2[10],charresult[10]){strcpy(QUAD[Index].op,op);strcpy(QUAD[Index].arg1,arg1);strcpy(QUAD[Index].arg2,arg2);

20

Page 21: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

sprintf(QUAD[Index].result,"t%d",tIndex++);strcpy(result,QUAD[Index++].result);}yyerror(){printf("\n Error on line no:%d",LineNo);}

Input:

$vi test.c

main(){int a,b,c;if(a<b){a=a+b;}while(a<b){ a=a+b;}if(a<=b){ c=a- b;}else{ c=a+b;}}OUTPUT:$ lex int.l$ yacc –d int.y$ gcc lex.yy.c y.tab.c –ll –lm$ ./a.out test.c

21

Page 22: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

22

Page 23: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

Exp. No. 6 Implementation of Type Checking (Shift Reduce Parser)

#include<stdio.h>#include<conio.h>#include<string.h>struct prodn{

char p1[10];char p2[10];

};void main(){

char input[20],stack[50],temp[50],ch[2],*t1,*t2,*t;int i,j,s1,s2,s,count=0;struct prodn p[10];FILE *fp=fopen("sr_input.c","r");stack[0]='\0';clrscr();printf("\n Enter the input string\n");scanf("%s",&input);while(!feof(fp)){

fscanf(fp,"%s\n",temp);t1=strtok(temp,"->");t2=strtok(NULL,"->");strcpy(p[count].p1,t1);strcpy(p[count].p2,t2);count++;

}i=0;while(1){

if(i<strlen(input)){

ch[0]=input[i];ch[1]='\0';i++;strcat(stack,ch);printf("%s\n",stack);

}for(j=0;j<count;j++){

t=strstr(stack,p[j].p2);if(t!=NULL){

23

Page 24: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

s1=strlen(stack);s2=strlen(t);s=s1-s2;stack[s]='\0';strcat(stack,p[j].p1);printf("%s\n",stack);j=-1;

}}if(strcmp(stack,"E")==0&&i==strlen(input)){

printf("\n Accepted");break;

}if(i==strlen(input)){

printf("\n Not Accepted");break;

}}getch();

}

Input File: sr_input.c

E->E+EE->E*EE->i

7A.  Implement control flow analysis

AIM:

   To write a C program to implement Control Flow Analysis.

INTRODUCTION:

Control flow analysis can be represented by basic blocks. It depicts how the program control is being passed among the blocks.

24

Page 25: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

ALGORITHM:

Step-1: Start the Program Execution.

Step-2: Declare the necessary variables for accessing statements from cdp7.txtStep-3: Find out the Leaders, Conditional Statements and blocks from the file.Step-4: Display the blocks with Block No.Step-5: Display the Control flow movement with block Number.Step-6: Stop the Program Execution.

PROGRAM

CDP7A.C# include<stdio.h># include<conio.h>#include<alloc.h>#include<string.h>struct Listnode{

char data[50];int leader,block,u_goto,c_goto;struct Listnode *next;char label[10],target[10];

}*temp,*cur,*first=NULL,*last=NULL,*cur1;

FILE *fpr;void createnode(char code[50]){ temp=(struct Listnode *)malloc(sizeof(struct Listnode)); strcpy(temp->data,code);

strcpy(temp->label,'\0');strcpy(temp->target,'\0');temp->leader=0;temp->block=0;temp->u_goto=0;temp->c_goto=0;temp->next=NULL;

if(first==NULL){

first=temp;last=temp;

}else{

last->next=temp;

25

Page 26: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

last=temp;}}

void main(){

char codeline[50];char c,dup[50],target[10];char *substring,*token;int i=0,block,block1;int j=0;fpr= fopen("CDP7.txt","r");clrscr();while((c=getc(fpr))!=EOF){

if(c!='\n'){

codeline[i]=c;i++;

}else{

codeline[i]='\0';createnode(codeline);i=0;

}}//create last nodecodeline[i]='\0';createnode(codeline);fclose(fpr);// find out leaders,conditional stmtscur=first;cur->leader=1;while(cur!=NULL){

substring=strstr((cur->data),"if");if(substring==NULL){

if((strstr((cur->data),"goto"))!=NULL){

cur->u_goto=1;(cur->next)->leader=1

}}

26

Page 27: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

else{

cur->c_goto=1;(cur->next)->leader=1;

}substring=strstr((cur->data),":");if(substring!=NULL){

cur->leader=1;}substring=strstr((cur->data),"call");if(substring!=NULL){

cur->leader=1;}if(strstr(cur->data,"return")!=NULL){

cur->leader=1;(cur->next)->leader=1;

}cur=cur->next;}//to find labels and targetscur=first;while(cur!=NULL){

if((cur->u_goto==1)||(cur->c_goto==1)){

substring=strstr(cur->data,":");if(substring!=NULL){

token=strstr(substring,"L" );if(token!=NULL)strcpy(cur->target,token);

}else{

substring=strstr(cur->data,"L");if(substring!=NULL)strcpy(cur->target,substring);

}}

if(strstr(cur->data,":")!=NULL){

27

Page 28: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

strcpy(dup,cur->data);token=strtok(dup,":");// printf("\ntoken:%s",token);if(token!=NULL)strcpy(cur->label,token);

}cur=cur->next;}//to identify blockscur=first;while(cur!= NULL){

cur=cur->next;if((cur->leader)==1){

j++;cur->block=j;

}elsecur->block=j;}printf("\n\n......Basic Blocks......\n");cur=first;j=0;printf("\nBlock %d:",j);while(cur!=NULL){

if ((cur->block)==j){

printf("%s",cur->data);printf("\n\t");cur=cur->next;}else{j++;printf("\nBlock %d:",j);}

}//to output the control flow from each blockprintf ("\t\t.......Control Flow.......\n\n");cur=first;i=0;

28

Page 29: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

while(cur!=NULL){if((cur->block)!=(cur->next)->block){block=cur->block;if(cur->u_goto==1){strcpy(target,cur->target);cur1=first;while(cur1!=NULL){if(strcmp(cur1->label,target)==0){block1=cur1->block;printf("\t\tBlock%d---------->Block%d\n",block,block1);}cur1=cur1->next;}}else if(cur->c_goto==1){strcpy(target,cur->target);cur1=first;while(cur1!=NULL){if(strcmp(cur1->label,target)==0){block1=cur1->block;printf("\t\tBlock%d---TRUE--->Block%d---FALSE--->Block%d\n",block,block1,(block+1));}cur1=cur1->next;}}else if(strstr(cur->data,"return")==NULL){printf("\t\tBlock%d---------->Block%d\n",block,(block+1));}elseprintf("\t\tBlock%d---------->NULL\n",block);}

cur=cur->next;}cur=last;block= cur->block;

29

Page 30: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

printf("\t\tBlock%d--------->NULL",block);getch();}

CDP7.TXT

m <- 0v <- 0L1 :  if v < n goto L2r <- vs <- 0returnL2 : if r >= n goto L1v <- v + 1

OUTPUT:

......Basic Blocks......

Block 0:m <- 0        v <- 0

Block 1:L1 :  if v < n goto L2

Block 2:r <- v        s <- 0

Block 3:return

Block 4:L2 : if r >= n goto L1

Block 5:v <- v + 1

.......Control Flow.......

                Block0---------->Block1                Block 1---TRUE--->Block 4---FALSE--->Block 2                   Block2---------->Block3 Block3---------->NULL Block 4---TRUE--->Block 1---FALSE--->Block 5                Block5--------->NULL

30

Page 31: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

RESULT:

Thus the above program is compiled and executed successfully and output is verified.

Ex. No: 7 BDate:

7B.  Implement Data flow analysis 

AIM:

   To write a C program to implement Data Flow Analysis.

INTRODUCTION:

Data flow analysis is a technique for gathering information about the possible set of value calculated at various points in a computer program.

ALGORITHM:

Step-1: Start the Program Execution.Step-2: Read the total Numbers of Expression Step-3: Read the Left and Right side of Each Expressions Step-4: Display the Expressions with Line NoStep-5: Display the Data flow movement with Particular Expressions Step-6: Stop the Program Execution.

PROGRAM

#include <stdio.h>#include <conio.h>#include <string.h >

31

Page 32: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

struct op{

char l[20];char r[20];

}op[10], pr[10];

void main(){

int a, i, k, j, n, z = 0, m, q,lineno=1;char * p, * l;char temp, t;char * tem;char *match;clrscr();printf("enter no of values");scanf("%d", & n);for (i = 0; i < n; i++){

printf("\tleft\t");scanf("%s",op[i].l);printf("\tright:\t");scanf("%s", op[i].r);

}printf("intermediate Code\n");for (i = 0; i < n; i++){   

printf("Line No=%d\n",lineno);printf("\t\t\t%s=", op[i].l);printf("%s\n", op[i].r);lineno++;

}printf("***Data Flow Analysis for the Above Code ***\n");for(i=0;i<n;i++){

for(j=0;j<n;j++){

match=strstr(op[j].r,op[i].l);if(match){

printf("\n %s is live at  %s \n ", op[i].l,op[j].r);}

}} }OUTPUT:

Enter no of values4

32

Page 33: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

        left    a        right:  a+b        left    b        right:  a+c        left    c        right:  a+b        left    d        right:  b+c+d Line No=1 a=a+b Line No=2 b=a+cLine No=3                        c=a+bLine No=4                        d=b+c+d***Data Flow Analysis for the Above Code ***

 a is live at  a+b

 a is live at  a+c

 a is live at  a+b

 b is live at  a+b

 b is live at  a+b

 b is live at  b+c+d

 c is live at  a+c

 c is live at  b+c+d

 d is live at  b+c+d

RESULT:

Thus the above program is compiled and executed successfully and output is verified.

33

Page 34: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

Exp.no.8IMPLEMENT ANY ONE STORAGE ALLOCATION STRATEGIES(HEAP,STACK,STATIC)AIM:To write a C program for Stack to use dynamic storage allocation.INTRODUCTION:Storage AllocationRuntime environment manages runtime memory requirements for the following entities:Code: It is known as the part of a program that does not change at runtime. Itsmemory requirements are at the compile timeProcedures: Their text part is static but they are called in a random manner. That iswhy, stack storage is used to manage procedure calls and activations.Variables: Variables are known at the runtime only, unless they are global or constant.Heap memory allocation scheme is used for managing allocation and de-allocation ofmemory for variables in runtime.ALGORITHM:1. Start the program2. Enter the expression for which intermediate code is to be generated3. If the length of the string is greater than 3, than call the procedure to return theprecedence4. Among the operands.5. Assign the operand to exp array and operators to the array.6. Create the three address code using quadruples structure.7. Reduce the no of temporary variables.8. Continue this process until we get an output.9. Stop the program.#include <stdio.h>#include <conio.h>#include <process.h>#include <alloc.h>struct node{

int label;struct node *next;

};void main(){

int ch = 0;int k;struct node *h, *temp, *head;head = (struct node*) malloc(sizeof(struct node));head->next = NULL;while(1){

printf("\n Stack using Linked List \n");printf("1->Push ");

34

Page 35: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

printf("2->Pop ");printf("3->View");printf("4->Exit \n");printf("Enter your choice : ");scanf("%d", &ch);switch(ch){

case 1:temp=(struct node *)(malloc(sizeof(struct node)));printf("Enter label for new node : ");scanf("%d", &temp->label);h = head;temp->next = h->next;h->next = temp;break;

case 2:h = head->next;head->next = h->next;printf("Node %s deleted\n", h->label);free(h);break;

case 3:printf("\n HEAD -> ");h = head;while(h->next != NULL){

h = h->next;printf("%d -> ",h->label);

}printf("NULL \n");break;

case 4:exit(0);

}} }

35

Page 36: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

EX.NO:9DATE:CONSTRUCTION OF DAGAIM:To write a C program to construct of DAG(Directed Acyclic Graph)INTRODUCTION:The code optimization is required to produce an efficient target code. These are two importantissues that used to be considered while applying the techniques for code optimization.They are:The semantics equivalences of the source program must not be changed.The improvement over the program efficiency must be achieved without changing the

36

Page 37: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

algorithm.ALGORITHM:1. Start the program2. Include all the header files3. Check for postfix expression and construct the in order DAG representation4. Print the output5. Stop the program

PROGRAM: (TO CONSTRUCT OF DAG(DIRECTED ACYCLIC GRAPH))

#include<stdio.h>void main(){

struct da{

int ptr,left,right;char label;

}dag[25];int ptr,l,j,change,n=0,i=0,state=1,x,y,k;char store,*input1,input[25],var;clrscr();for(i=0;i<25;i++){

dag[i].ptr=NULL;dag[i].left=NULL;dag[i].right=NULL;dag[i].label=NULL;

}printf("\n\nENTER THE EXPRESSION\n\n");scanf("%s",input1);/*EX:((a*b-c))+((b-c)*d)) like this give with paranthesis.limitis 25 char ucan change that*/for(i=0;i<25;i++)

input[i]=NULL;l=strlen(input1);a:

for(i=0;input1[i]!=')';i++);for(j=i;input1[j]!='(';j--);for(x=j+1;x<i;x++)

if(isalpha(input1[x]))input[n++]=input1[x];

elseif(input1[x]!='0')

store=input1[x];input[n++]=store;for(x=j;x<=i;x++)

input1[x]='0';

37

Page 38: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

if(input1[0]!='0')goto a;

for(i=0;i<n;i++){

dag[i].label=input[i];dag[i].ptr=i;if(!isalpha(input[i])&&!isdigit(input[i])){

dag[i].right=i-1;ptr=i;var=input[i-1];if(isalpha(var))

ptr=ptr-2;else{

ptr=i-1;b:

if(!isalpha(var)&&!isdigit(var)){

ptr=dag[ptr].left;var=input[ptr];goto b;

}else

ptr=ptr-1;}dag[i].left=ptr;

}}printf("\n SYNTAX TREE FOR GIVEN EXPRESSION\n\n");printf("\n\n PTR \t\t LEFT PTR \t\t RIGHT PTR \t\t LABEL\n\n");for(i=0;i<n;i++) /* draw the syntax tree for the following output with

pointer value*/printf("\n%d\t%d\t%d\t%c\n",dag[i].ptr,dag[i].left,dag[i].right,dag[i].label);

getch();for(i=0;i<n;i++){

for(j=0;j<n;j++){

if((dag[i].label==dag[j].label&&dag[i].left==dag[j].left)&&dag[i].right==dag[j].right){

for(k=0;k<n;k++){

if(dag[k].left==dag[j].ptr)dag[k].left=dag[i].ptr;

38

Page 39: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

if(dag[k].right==dag[j].ptr)dag[k].right=dag[i].ptr;}dag[j].ptr=dag[i].ptr;

}}

}printf("\n DAG FOR GIVEN EXPRESSION\n\n");printf("\n\n PTR \t LEFT PTR \t RIGHT PTR \t LABEL \n\n");for(i=0;i<n;i++) /*draw DAG for the following output with pointer value*/

printf("\n %d\t\t%d\t\t%d\t\t%c\n",dag[i].ptr,dag[i].left,dag[i].right,dag[i].label);getch();

}

39

Page 40: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

Exp .No. 10Implementation of back end of the compiler using c

#include<stdio.h>#include<string.h>void printop(char *op){

if(strcmp(op,"+")==0)printf("\t ADD ");else if(strcmp(op,"-")==0)printf("\t SUB ");else if(strcmp(op,"*")==0)printf("\t MUL ");else if(strcmp(op,"/")==0)printf("\t DIV ");

}void main(){

char line[20];char *exp,*res,*op1,*op2,*op;char RO[10];int ch;FILE *fp=fopen("input.c","r");clrscr();RO[0]='\0';printf("Code is generated\n\n");while(!feof(fp)){

fscanf(fp,"%s\n",line);res=strtok(line,"=");exp=strtok(NULL,"=");if(strstr(exp,"+")!=0){

op1=strtok(exp,"+");op2=strtok(NULL,"+");strcpy(op,"+");

40

Page 41: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

}else if(strstr(exp,"-")!=0){

op1=strtok(exp,"-");op2=strtok(NULL,"-");strcpy(op,"-");

}else if(strstr(exp,"*")!=0){

op1=strtok(exp,"*");op2=strtok(NULL,"*");strcpy(op,"*");

}else if(strstr(exp,"/")!=0){

op1=strtok(exp,"/");op2=strtok(NULL,"/");strcpy(op,"/");

}if(strcmp(RO,op1)!=0){

if(strcmp(RO,op2)!=0){

printf("\t MOV ");printf("%s,RO \n",op1);printop(op);printf("%s,RO\n",op2);

}else{

printop(op);printf("%s,RO\n",op1);

}}else{

printop(op);printf("%s,RO\n",op2);

}printf("\t MOV RO,%s\n",res);strcpy(RO,res);

}getch();

}

41

Page 42: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

Input.cT0=a+bT1=T0*cT2=T1/d

Ex. No: 11Date:

11. Implementation of Simple Code Optimization Techniques (ConstantFolding.,etc.)

AIM:To write a C program to implement the code optimization techniques.ALGORITHM:1. Start2. Create an input file which contains three address code.3. Open the file in read mode.4. If the file pointer returns NULL, exit the program else go to 5.5. Scan the input symbol from the left to right. Common Sub expression elimination6. Store the first expression in a string.7. Compare the string with the other expressions in the file.8. If there is a match, remove the expression from the input file.9. Perform these steps 5 to 8 for all the input symbols in the file. Dead code Elimination10. Scan the input symbol from the file from left to right.11. Get the operand before the operator from the three address code.12. Check whether the operand is used in any other expression in the three address code.13. If the operand is not used, then eliminate the complete expression from the three address code else go to 14.14. Perform steps 11 to 13 for all the operands in the three address code till end of file is reached.15.Stop..

PROGRAM#include <stdio.h>#include <conio.h>#include <string.h >struct op{

char l;char r[20];

}op[10], pr[10];void main(){

42

Page 43: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

int a, i, k, j, n, z = 0, m, q;char * p, * l;char temp, t;char * tem;clrscr();printf("enter no of values");scanf("%d", & n);for (i = 0; i < n; i++){

printf("\tleft\t");op[i].l = getche();printf("\tright:\t");scanf("%s", op[i].r);

}printf("intermediate Code\n");for (i = 0; i < n; i++){

printf("%c=", op[i].l);printf("%s\n", op[i].r);

}for (i = 0; i < n - 1; i++){

temp = op[i].l;for (j = 0; j < n; j++){

p = strchr(op[j].r, temp);if (p){

pr[z].l = op[i].l;strcpy(pr[z].r, op[i].r);z++;

}}

}pr[z].l = op[n - 1].l;strcpy(pr[z].r, op[n - 1].r);z++;printf("\nafter dead code elimination\n");for (k = 0; k < z; k++){

printf("%c\t=", pr[k].l);printf("%s\n", pr[k].r);

}//sub expression eliminationfor (m = 0; m < z; m++){

43

Page 44: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

tem = pr[m].r;for (j = m + 1; j < z; j++){

p = strstr(tem, pr[j].r);if (p){

t = pr[j].l;pr[j].l = pr[m].l;for (i = 0; i < z; i++){

l = strchr(pr[i].r, t);if (l) {

a = l - pr[i].r;//printf("pos: %d",a);pr[i].r[a] = pr[m].l;

}}

}}

}printf("eliminate common expression\n");for (i = 0; i < z; i++) {

printf("%c\t=", pr[i].l);printf("%s\n", pr[i].r);

}// duplicate production eliminationfor (i = 0; i < z; i++){

for (j = i + 1; j < z; j++){

q = strcmp(pr[i].r, pr[j].r);if ((pr[i].l == pr[j].l) && !q){

pr[i].l = '\0';strcpy(pr[i].r, '\0');

}}

}printf("optimized code");for (i = 0; i < z; i++){

if (pr[i].l != '\0') {

printf("%c=", pr[i].l);

44

Page 45: nasrinword.files.wordpress.com  · Web viewExp.No. : 1. IMPLEMENTATION OF SYMBOL TABLE (TOKEN SEPARATION) #include #include //#include

printf("%s\n", pr[i].r);}

} getch();

}

OUTPUT:left a right: 9left b right: c+dleft e right: c+dleft f right: b+eleft r right: fintermediate Codea=9b=c+de=c+df=b+er=fafter dead code eliminationb =c+de =c+df =b+er =feliminate common expressionb =c+db =c+df =b+br =foptimized codeb=c+df=b+br=fRESULT:Thus the above program is compiled and executed successfully and output is verified.

45