++++imp compiler c programs

64
INDEX Expt No. Name of the Experiment Date Page No. Marks Awarded Signature SYSTEM SOFTWARE 1. SYMBOL TABLE 31-01-2007 2. ASSEMBLER 07-02-2007 3. LOADER 14-02-2007 4. MACROPROCESSOR 07-03-2007 COMPILER DESIGN 5. CONSTRUCTING NFA FROM REGULAR EXPRESSION 10-03-2007 6. CONSTRUCTING DFA FROM REGULAR EXPRESSION 14-03-2007 7. CONSTRUCTION OF TOP DOWN PARSER 28-03-2007 8. SHIFT REDUCE PARSING 04-04-2007 9. OPERATOR PRECEDENCE PARSING 04-04-2007 10. INTERMEDIATE CODE GENERATOR 11-04-2007 11. LR PARSING TABLE SYMBOL TABLE

Upload: ramneet

Post on 24-Apr-2015

442 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: ++++Imp Compiler c Programs

INDEX

Expt No.

Name of the Experiment Date Page No.

Marks Awarded

Signature

SYSTEM SOFTWARE

1. SYMBOL TABLE 31-01-2007

2. ASSEMBLER 07-02-2007

3. LOADER 14-02-2007

4. MACROPROCESSOR 07-03-2007

COMPILER DESIGN

5. CONSTRUCTING NFA FROM REGULAR EXPRESSION

10-03-2007

6. CONSTRUCTING DFA FROM REGULAR EXPRESSION

14-03-2007

7. CONSTRUCTION OF TOP DOWN PARSER

28-03-2007

8. SHIFT REDUCE PARSING

04-04-2007

9. OPERATOR PRECEDENCE PARSING

04-04-2007

10. INTERMEDIATE CODE GENERATOR

11-04-2007

11. LR PARSING TABLE

SYMBOL TABLE

Page 2: ++++Imp Compiler c Programs

AIM:

To write a C program to generate the symbol table of the compiler.

ALGORITHM:

1. Start the program.

2. A structure is created & variables are declared.

3. Define the main function.

4. Create an array which contains the different data types.

5. Create the second array for storing the size.

6. Create a file pointer fp.

7. Enter the name of file which has already been created.

8. Open the file using ‘fopen’.

9. Initialize the variable ‘I’ and ‘sp’ to ‘0’.

10. Start the for loop and continue till the condition satisfies.

11.Scan the file and compare each character of the file with array of data

type and if equals then go to step 10.

12. Check for semicolon, if found goto step 11.

13.Move the data type to the st[i].t,the size to the st[i].s and the variable to the

st[i].v.

14. Do the step 9 until the ‘eof’ is reached.

15. Display the content of structure.

16. If two entries are same then display “multiple declaration”.

17. Display and print the output accordingly.

18. Stop the program.

Page 3: ++++Imp Compiler c Programs

PROGRAM:

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

char v[10],t[10];int s;

} st[50];char *tt[] = {"int","float","long","double","short"};int vt[5]= {2,4,6,8,1};FILE *fp;void main(){

char *fn,u[20],t[20],s[100],*p;int i=0,j,k,l,y,sp=0;clrscr();printf("\n Enter file name: ");scanf("%s",fn);printf("\n The given file name is %s",fn);fp=fopen(fn,"r");printf("\nSymbol table maintenance");printf("\n\tVariable\tType\t\tsize\n");while(!feof(fp)){

fscanf(fp,"%s",s);for(i=0;i<5;i++)if(strcmp(s,tt[i])==0){

fscanf(fp,"%s",s);p=strchr(s,',');if(p){

j=0;while(s[j]!=',')j++;for(k=0;k<j;k++)t[k]=s[k];t[k]='\0';printf("\n%10s\t%10s\t%10d",t,tt[i],vt[i]);strcpy(st[sp].v,t);strcpy(st[sp].t,tt[i]);st[sp].s=vt[i];sp++;kjk:

Page 4: ++++Imp Compiler c Programs

y=j;j++;while(s[j]!='\0'&&s[j]!=',')j++;for(l=y;l<j;l++)t[l-2]='\0';printf("\n%10s\t%10s\t%10d",t,tt[i],vt[i]);strcpy(st[sp].t,tt[i]);st[sp].s=vt[i];sp++;if(s[j]==',')goto kjk;

}else{

printf("\n%10s\t%10s\t%10d",s,tt[i],vt[i]);strcpy(st[sp].v,t);strcpy(st[sp].t,tt[i]);st[sp].s=vt[i];

}}

}fclose(fp);for(i=0;i<sp;i++)strcpy(t,st[i].v);k=0;for(j=0;j<strlen(t);j++){

if(t[i]!=','){

u[k]=u[j];k++;

}u[k]='\0';strcpy(st[i].v,u);

}for(i=0;i<sp-2;i++)for(j=i+1;j<sp;j++){

if(strcmp(st[i].v,st[j].v)==0)printf("\n\nMultiple Declaration for %s",st[i].v);

}getch();

}

INPUT FILE:

Page 5: ++++Imp Compiler c Programs

Out.c

main(){int afloat bdouble clong d}

OUTPUT:

Page 6: ++++Imp Compiler c Programs

Enter file name: out.c

The given file name is out.cSymbol table maintenance

Variable Type size

a int 2 b float 4 c double 8 d long 6

Page 7: ++++Imp Compiler c Programs

RESULT: Hence, the given program has been executed and the output has been

verified successfully.

Page 8: ++++Imp Compiler c Programs

ASSEMBLER

AIM:

To write a C program to execute an assembly language program.

ALGORITHM:

1. Start the program.

2. Declare the necessary header files.

3. Define the main function.

4. Declare array for data & reg and other necessary variables.

5. Create an input file and open it using ‘fopen’.

6. Scan each character of the file, if not equal to ‘eof’ then process step 7

to 17.

7. Scan each line of the file and print accordingly.

8. Compare the string with the instruction and perform the operation.

9. Move the first data to regA and assign the value of regA to variable a.

10. Move the first data to regB and assign the value of regA to variable b.

11. Start ‘if’ statement and perform the operation accordingly.

12. Identify the type of instruction and perform the steps 12 to 16.

13. Assign the variables ‘a’ & ‘b’ to ‘I’ & ‘J’.

14. Add the content of ‘a’ & ‘b’ if instruction “ADD” and print the result.

15. Subtract the content of ‘a’ & ‘b’ if instruction “SUB” and print the result.

16. Multiply the content of ‘a’ & ‘b’ if instruction “MUL” and print the result.

17. Print and display the output according to the operation performed.

18. End the program.

PROGRAM:

Page 9: ++++Imp Compiler c Programs

# include<stdio.h># include<conio.h># include<string.h># include<ctype.h># include<stdlib.h>void main(){

FILE *f;char x[40],data[40],reg[40];int a=0,b=0,i,j,result=0,temp,c,d;clrscr();printf("\t\tOUTPUT\n");f=fopen("res.cpp","r");while(!feof(f)){

fscanf(f,"%s",x);if(strcmp(x,"STOP")==0)

exit(0);else if(strcmp(x,"MVI")==0){

fscanf(f,"%s%s",reg,data);if(strcmp(reg,"AREG,")==0) a=atoi(data);else if(strcmp(reg,"BREG,")==0)

b=atoi(data);}else{

if(strcmp(x,"ADD")==0){

result=a+b;printf("\n\tI:%d",a);printf("\n\tJ:%d",b);printf("\nRESULT(I+J):%d",result);

}else if(strcmp(x,"SUB")==0){

result=a-b;printf("\n\tI:%d",a);printf("\n\tJ:%d",b);printf("\nResult(I-J):%d",result);

}else if(strcmp(x,"MUL")==0){

result=a*b;printf("\nI:%d",a);

Page 10: ++++Imp Compiler c Programs

printf("\nJ:%d",b);printf("\nresult(I*J):%d",result);

}getch();

}}

}

INPUT FILE:

Page 11: ++++Imp Compiler c Programs

MVI AREG, 10MVI BREG, 15ADD AREG, BREGMOVE RES, AREGPRINT RESRes DS 1STOP

Page 12: ++++Imp Compiler c Programs

OUTPUT:

OUTPUT I:10 J:15RESULT(I+J):25

Page 13: ++++Imp Compiler c Programs

RESULT: Hence, the given program has been executed and the output has been

verified successfully.

Page 14: ++++Imp Compiler c Programs

LOADER

AIM:

To write a C program to generate the function of loader.

ALGORITHM:

1. Start the program.

2. Define the main function.

3. Declare array for string and other necessary variables.

4. Create an input file having header text, text record and end of file.

5. Open the file using ’fopen’ and assign it to file pointer fp.

6. Print error if the file is empty.

7. Using ‘fgetc’ check the variable c is not equal to the Haeder Text ‘H’ then

print as “Error Occur”.

8. Else assign the length of the string and print “Program Name”.

9. Using ‘fgets’ assign the length of the address and print “Address”

10. With ‘fgetc’ c is checked whether it is equal to Text Record “T”.

11. Initialize the variable ‘I’ and start the loop till it satisfies the condition.

12. Perform the operation for the variable ‘add’ and print the result.

13. Get the results using ‘fgets’ and print “Length” of the program.

14. Continue do while loop until the program encounters the ‘End of file’.

15.From the input file, fetch the program name,address and length of the

program and print accordingly.

16.Define the length of the string using ‘fgets’ and print “Program Address

Contents”.

17. Display the starting address and remaining contents of the program.

18. Display the output

19. End the program

PROGRAM:

Page 15: ++++Imp Compiler c Programs

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

int add,i,value;char str[10],c,ad[10],cn[10];FILE *fp;clrscr();fp=fopen("AAA1.txt","r");if (fp==NULL){

printf("\ERROR");exit(0);

}else{

c=fgetc(fp);if (c!='H'){

printf("\ERROR OCCUR");exit(0);

}}fgets(str,7,fp);printf("\nProgarm name:%s",str);fgets(ad,7,fp);printf("\nAddress:%s",ad);fgets (cn,8,fp);printf("\nLENGTH:%s",cn);add=atoi(ad);printf("\nProgram Address Contents \n");fgets (str,2,fp);printf("%d\t",add);c=fgetc(fp);do{

if (c=='T'){

fgets(str,1,fp);i=6;

}if (i==6){

add=add+10;printf("%d\t",add);

Page 16: ++++Imp Compiler c Programs

i=0;}else{

printf("%c",c);}c=fgetc(fp);

}while (c!='E');getch();

}

INPUT FILE:

Page 17: ++++Imp Compiler c Programs

AAA1.txt

Hharesh00100000077T1410334B2039010362BT0310364B206148E001000

Page 18: ++++Imp Compiler c Programs

OUTPUT:

Program Name:hareshADDRESS:001000LENGTH:00077Program Address Contents1000 1410334B2039010362B1010 0310364B206148

Page 19: ++++Imp Compiler c Programs

RESULT: Hence, the given program has been executed and the output has been

verified successfully.

MACROPROCESSOR

Page 20: ++++Imp Compiler c Programs

AIM:

To write a C program to generate the macroprocessor.

ALGORITHM:

1. Start the program.

2. Declare the necessary header files and other variables.

3. Define the main function.

4. Declare array for variable a & b and other data types.

5. Create 3 file pointers as fp,f1,f2.

6. Initialize the variable I & temp to ‘0’.

7. Create 2 input files containing macros and expansion of macros .

8. Open the file using ‘fopen’ and start performing the while loop.

9. Scan each line of the file until it encounters the ‘EOF’.

10. If ‘ch’ encounters the operator ‘;’ then perform the necessary steps.

11. Compare the string ‘a’ & ‘b’ and check whether it is equal to ‘0’.

12. Open the second file and perform the operation.

13. Using ‘fgetc’ scan each line of the file until it encounters the ‘EOF’.

14. Print the encountered string and put the string in the file f2 using ‘fputc’.

15. Start the for loop and continue til it satisfies the condition.

16. Using ‘fputs’ put the encountered string in file f2.

17. Repeat the steps 9 to 16 till the condition fails.

18. Close all files using ‘fclose’ and display the output.

19. End the program.

PROGRAM:

Page 21: ++++Imp Compiler c Programs

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

FILE *fp,*f1,*f2;char ch,ch1;char a[100];char b[]="macro";int i=0,j,temp=0;clrscr();fp=fopen("sys.txt","r");f2=fopen("sys3.txt","w");while((ch=fgetc(fp))!=EOF){

a[i]=ch;if(ch==';'||ch=='\n'){

a[i]=0;temp=0;if(strcmp(b,a)==0){f1=fopen("sys2.txt","r");while((ch1=fgetc(f1))!=EOF){

printf("%c",ch1);fputc(ch1,f2);temp=1;

}if(temp==1){

for(j=0;j<i+1;j++)a[i]=0;i=0;continue;

}}printf("%s",a);fputs(a,f2);for(j=0;j<i+1;j++)a[i]=0;i=0;continue;

}i++;

Page 22: ++++Imp Compiler c Programs

}fclose(fp);fclose(f1);fclose(f2);getch();

}

INPUT FILE:

Page 23: ++++Imp Compiler c Programs

Sys.txt

#include<stdio.h>#include<conio.h>void main(){macro;}

Sys2.txt

int a,b,c;c=a+b;printf("%d",c);

OUTPUT:

Page 24: ++++Imp Compiler c Programs

#include<stdio.h>#include<conio.h>void main(){int a,b,c;c=a+b;printf("%d",c);

Sys3.txt

Page 25: ++++Imp Compiler c Programs

RESULT: Hence, the given program has been executed and the output has been

verified successfully.

Page 26: ++++Imp Compiler c Programs

NFA FROM RE

AIM:

To write a C program to convert the regular expression to NFA.

ALGORITHM:

1. Start the program.

2. Declare all necessary header files.

3. Define the main function.

4. Declare the variables and initialize variables r & c to ‘0’.

5. Use a for loop within another for loop to initialize the matrix for NFA

states.

6. Get a regular expression from the user & store it in ‘m’.

7. Obtain the length of the expression using strlen() function and store it in

‘n’.

8. Use for loop upto the string length and follow steps 8 to 12.

9. Use switch case to check each character of the expression.

10. If case is ‘/’, set the links as ‘E’ or suitable inputs as per rules.

11. If case is ‘*’, set the links as ‘E’ or suitable inputs as per rules.

12. If case is ‘+’, set the links as ‘E’ or suitable inputs as per rules.

13.Check the default case, i.e.,for single alphabet or 2 consecutive

alphabets and set the links to respective alphabet.

14. End the switch case.

15. Use for loop to print the states along the matrix.

16.Use a for loop within another for lop and print the value of respective links.

17. Print the states start state as ‘0’ and final state.

18. End the program.

Page 27: ++++Imp Compiler c Programs

PROGRAM:

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

void main(){char m[20],t[10][10];int n,i,j,r=0,c=0;clrscr();printf("\n\t\t\t\tSIMULATION OF NFA");printf("\n\t\t\t\t*****************");for(i=0;i<10;i++){for(j=0;j<10;j++){t[i][j]=' ';}}printf("\n\nEnter a regular expression:");scanf("%s",m);n=strlen(m);for(i=0;i<n;i++){switch(m[i]){case '|' : {

t[r][r+1]='E';t[r+1][r+2]=m[i-1];t[r+2][r+5]='E';t[r][r+3]='E';t[r+4][r+5]='E';t[r+3][r+4]=m[i+1];r=r+5;break;}

case '*':{t[r-1][r]='E';t[r][r+1]='E';t[r][r+3]='E';t[r+1][r+2]=m[i-1];t[r+2][r+1]='E';t[r+2][r+3]='E';r=r+3;break;}

Page 28: ++++Imp Compiler c Programs

case '+': {t[r][r+1]=m[i-1];t[r+1][r]='E';r=r+1;break;}default:{

if(c==0){

if((isalpha(m[i]))&&(isalpha(m[i+1]))){t[r][r+1]=m[i];t[r+1][r+2]=m[i+1];r=r+2;c=1;}c=1;

}else if(c==1){

if(isalpha(m[i+1])){t[r][r+1]=m[i+1];r=r+1;

c=2;}

}else{

if(isalpha(m[i+1])){t[r][r+1]=m[i+1];r=r+1;c=3;}

}}

break;}}printf("\n");for(j=0;j<=r;j++)printf(" %d",j);printf("\n___________________________________\n");

Page 29: ++++Imp Compiler c Programs

printf("\n");for(i=0;i<=r;i++){for(j=0;j<=r;j++){printf(" %c",t[i][j]);}printf(" | %d",i);printf("\n");}printf("\nStart state: 0\nFinal state: %d",i-1);getch();}

OUTPUT:

Page 30: ++++Imp Compiler c Programs

Enter a regular Expression: a|b

SIMULATION OF NFA *****************

Enter a regular expression:a|b

0 1 2 3 4 5___________________________________

E E | 0 a | 1 E | 2 b | 3 E | 4 | 5

Start state: 0Final state: 5

Page 31: ++++Imp Compiler c Programs

RESULT: Hence, the given program has been executed and the output has been

verified successfully.

SIMULATION OF DFA

Page 32: ++++Imp Compiler c Programs

AIM: To write a C program to convert the regular expression to DFA.

ALGORITHM:

1. Start the program.

2. A structure is created and the variables are declared.

3. Define the main function.

4. Declare the array for states and inpstr.

5. Define the readtt function to initialize the number of states ,number of

inputs,and transition from one state to other.

6. Get the no. of states and no. of inputs from the user.

7. Start the for loop and continue till it satisfies the condition.

8. Print the states according to the condition.

9. Generate the initial and final states of the string.

10. Define the dfasimul function to simulate it step 10-16.

11. Initialize the variable start to ‘0’ and begin for loop.

12. Check whether start is equal to ‘-1’, then print “DFA Halted”.

13. Get the string from the user and save in ‘inpstr’.

14. Read the string and until the end-of-string reached do step 15.

15.Go from one state to other based on the transition entered and update

start by the final state.

16. Print “string is accepted” if a state is equal to nstates-1.

17. Else print “String is not accepted”.

18. Display the output.

19. End the program.

PROGRAM:

#include<stdio.h>

Page 33: ++++Imp Compiler c Programs

#include<conio.h>typedef struct{

int input[2];}state;

void readtt(state *states,int nstates,int ninps){

int state,inp;printf("Enter the state transition:\n");for(state=0;state<nstates;state++)

for(inp=0;inp<ninps;inp++){

printf("(state:%d,%d):",state,inp);scanf("%d",&states[state].input[inp]);

}}

void dfasimul(state *states,int nstates,char *inpstr){

int i,start;start=0;for(i=0;inpstr[i]!='\0';i++){

start=states[start].input[inpstr[i]-'0'];}if(start==-1){

printf("DFA halted");return;

}else if(start==nstates-1)

printf("String is accepted");else

printf("String is not accepted");}void main(){

state states[100];int nstates,ninps;char inpstr[20];clrscr();printf("\n\t\t\t SIMULATION OF DFA");printf("\n\t\t\t *****************");printf("\nEnter the no. of states: ");scanf("%d",&nstates);

Page 34: ++++Imp Compiler c Programs

printf("Enter the no.of inputs: ");scanf("%d",&ninps);readtt(states,nstates,ninps);printf("\nInitial state: 0\nFinal state: %d",nstates-1);

printf("\n\nEnter the string: ");scanf("%s",inpstr);dfasimul(states,nstates,inpstr);getch();

}

OUTPUT:

Page 35: ++++Imp Compiler c Programs

SIMULATION OF DFA *****************Enter the no. of states: 2Enter the no.of inputs: 2Enter the state transition:(state:0,0):0(state:0,1):1(state:1,0):0(state:1,1):1

Initial state: 0Final state: 1

Enter the string: 1001String is accepted

Enter the no. of states: 2Enter the no.of inputs: 2Enter the state transition:(state:0,0):0(state:0,1):1(state:1,0):0(state:1,1):1

Initial state: 0Final state: 1

Enter the string: 0110String is not accepted

Page 36: ++++Imp Compiler c Programs

RESULT: Hence, the given program has been executed and the output has been

verified successfully.TOP DOWN PARSING

AIM:

Page 37: ++++Imp Compiler c Programs

To write a C program to implement top down parsing using arrays.

ALGORITHM:

1. Start the program.

2. A structure is created and the variables are declared.

3. Define the main function.

4. Declare the array for states and inpstr.

5. Define the readtt function to initialize the number of states ,number of

inputs,and transition from one state to other.

6. Get the no. of states and no. of inputs from the user.

7. Start the for loop and continue till it satisfies the condition.

8. Print the states according to the condition.

9. Generate the initial and final states of the string.

10. Define the dfasimul function to simulate it step 10-16.

11. Initialize the variable start to ‘0’ and begin for loop.

12. Check whether start is equal to ‘-1’, then print “DFA Halted”.

13. Get the string from the user and save in ‘inpstr’.

14. Read the string and until the end-of-string reached do step 15.

15.Go from one state to other based on the transition entered and update

start by the final state.

16. Print “string is accepted” if a state is equal to nstates-1.

17. Else print “String is not accepted”.

18. Display the output.

19. End the program.

PROGRAM:#include<iostream.h>#include<conio.h>

Page 38: ++++Imp Compiler c Programs

#include<string.h>#include<stdlib.h>void error(){

cout<<"not accepted";getch();exit(0);

}void main(){

clrscr();cout<<"Enter the string in single letter such as a+a*a \n\n";char string[10],stack[10];int i=0,k,top=0;cout<<"Enter the Expression :";cin>>string;int j=strlen(string);string[j]='$';string[++j]='\0';cout<<string<<endl;stack[top]='E';

cout<<"$"<<stack<<"\t"; for(k=i;k<j;k++) { cout<<string[k]; } cout<<endl;

top++; while(top!=0) { if(stack[top-1]==string[i]) { i++; top--; stack[top]='\0'; } else if(stack[top-1]=='E') { if(string[i]=='a') { top--; stack[top]='D'; stack[++top]='T'; top++; stack[top]='\0'; }

Page 39: ++++Imp Compiler c Programs

else if(string[i]=='(') { top--; stack[top]='D'; stack[++top]='T'; top++; stack[top]='\0'; } else error(); } else if(stack[top-1]=='D') { if(string[i]=='+') { top--; stack[top]='D'; stack[++top]='T'; stack[++top]='+'; top++; stack[top]='\0'; } else if(string[i]==')') { top--; stack[top]='\0'; } else if(string[i]=='$') { top--; stack[top]='\0'; } else error(); } else if(stack[top-1]=='T') { if(string[i]=='a') { top--; stack[top]='s'; stack[++top]='F'; top++; stack[top]='\0'; } else if(string[i]=='(') { top--;

Page 40: ++++Imp Compiler c Programs

stack[top]='s'; stack[++top]='F'; top++; stack[top]='\0'; } else error(); } else if(stack[top-1]=='s') { if(string[i]=='+') { top--; stack[top]='\0'; } else if(string[i]=='*') { top--; stack[top]='s'; stack[++top]='F'; stack[++top]='*'; top++; stack[top]='\0'; } else if(string[i]==')') { top--; stack[top]='\0'; } else if(string[i]=='$') { top--; stack[top]='\0'; } else error; } else if(stack[top-1]=='F') { if(string[i]=='a') { top--; stack[top]='a'; top++; stack[top]='\0'; } else if(string[i]=='(') {

Page 41: ++++Imp Compiler c Programs

top--; stack[top]=')'; stack[++top]='E'; stack[++top]='('; top++; stack[top]='\0'; } else error(); } else error();

cout<<"$"<<stack<<"\t"; for(k=i;k<j;k++) { cout<<string[k]; } cout<<endl; }cout<<"accepted";getch();

}

OUTPUT:

Enter the string in single letter such as a+a*a

Page 42: ++++Imp Compiler c Programs

enter the expression :a*a

a*a$

$E a*a$$DT a*a$$DsF a*a$$Dsa a*a$$Ds *a$$DsF* *a$$DsF a$$Dsa a$$Ds $$D $$ $

accepted

Page 43: ++++Imp Compiler c Programs

RESULT: Hence, the given program has been executed and the output has been

verified successfully.SHIFT REDUCE PARSING

AIM:

Page 44: ++++Imp Compiler c Programs

To write a C program to perform the shift reduce parsing.

ALGORITHM:

1. Start the program.

2. Define the main function.

3. Declare array for string and stack and other necessary variables.

4. Get the expression from the user and store it as string.

5. Append $ to the end of the string.

6. Store $ into the stack.

7. Print three columns as ‘Stack’, ‘String’ and ‘Action’ for the respective

actions.

8. Use for loop from i as 0 till string length and check the string.

9. If string has some operator or id, push it to the stack.

10. Mark this action as ‘Shift’.

11. Print the stack, string and action values.

12. If stack contains some production on shifting, reduce it.

13. Mark this action as ‘Reduce’.

14. Print the stack, string and action values.

15. Repeat steps 9 to 14 again and again till the for loop is valid.

16. Now check the string and the stack.

17.If the string contains only $ and the stack has only $E within it, then print

that the ‘given string is valid’.

18. Else print that the ‘given string is invalid’.

19. End the program.

PROGRAM:

Page 45: ++++Imp Compiler c Programs

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

char str[25],stk[25];int i,j,t=0,l,r;clrscr();printf("Enter the String : ");

scanf("%s",&str); l=strlen(str); str[l]='$'; stk[t]='$'; printf("Stack\t\tString\t\tAction\n-----------------------------------\n ");

for(i=0;i<l;i++) { if(str[i]=='i')

{t++;stk[t]=str[i];stk[t+1]=str[i+1];

for(j=0;j<=t+1;j++) printf("%c",stk[j]);

printf("\t\t "); for(j=i+2;j<=l;j++)

printf("%c",str[j]); printf("\t\tShift"); printf("\n "); stk[t]='E'; i++;

} else

{t++;

stk[t]=str[i];}

for(j=0;j<=t;j++)printf("%c",stk[j]);printf("\t\t ");for(j=i+1;j<=l;j++)printf("%c",str[j]);if(stk[t]=='+' || stk[t]=='*') printf("\t\tShift");else

Page 46: ++++Imp Compiler c Programs

printf("\t\tReduce");printf("\n ");

}

while(t>1) { if(stk[t]=='E' && (stk[t-1]=='+' || stk[t-1]=='*') && stk[t-2]=='E')

{ t-=2;

for(j=0;j<=t;j++) printf("%c",stk[j]); printf("\t\t"); printf(" %c",str[l]);

printf("\t\tReduce\n "); }

else t-=2;

}

if(t==1 && stk[t]!='+' && stk[t]!='*') printf("\nThe Given String is Valid\n\n");else printf("\nThe Given String is Invalid\n\n"); getch();

}

OUTPUT:

Page 47: ++++Imp Compiler c Programs

Enter the String : id+id*id

Stack String Action----------------------------------- $id +id*id$ Shift $E +id*id$ Reduce $E+ id*id$ Shift $E+id *id$ Shift $E+E *id$ Reduce $E+E* id$ Shift $E+E*id $ Shift $E+E*E $ Reduce $E+E $ Reduce $E $ Reduce

The Given String is Valid

Page 48: ++++Imp Compiler c Programs

RESULT: Hence, the given program has been executed and the output has been

verified successfully.

OPERATOR PRECEDENCE PARSING

Page 49: ++++Imp Compiler c Programs

AIM: To write a C program for implementin operator precedence parsing for given grammar.

ALGORITHM:

1. Start the program.

2. Declare all necessary header files and variables

3. Assign all the precedence relation for given grammer in a 2 d array

4. Get input from user in an array

5. Append $ symbol at the end of the input

6. Create stack using array and put $ as first element

7. Display the contents of stack and input array

8. If last element of stack and input is $ then the parsing is completed

9. Compare top of stack and top of input use find function to get element

10.If the symbol is space print parser error

11.If the symbol is < then shift top element of input to stack.

12.Display the contents of stack and input array

13.If the symbol is > then remove all elements from stack

14.Display the contents of stack and input array

15.End of the program.

Page 50: ++++Imp Compiler c Programs

PROGRAM:

#include<stdio.h>#include<conio.h>int find(char a){

switch(a){case 'a':return 0;case '+':return 1;case '*':return 2;case '$':return 3;}

}

void display(char a[],int top1,char b[],int top2){

int i;for(i=0;i<=top1;i++)printf("%c",a[i]);printf("\t");for(i=top2;i<strlen(b);i++)printf("%c",b[i]);printf("\n");

}int main(){

char table[][4]= {' ','>','>','>','<','<','<','>','<','>','<','>','<','<','<',' '};char input[10];char stack[10]={'$'};int top_stack=0,top_input=0,i,j;clrscr();printf("operator precedence parsing for E->E+E/E*E/a\n");printf("enter the string\n");scanf("%s",input);strcat(input,"$");printf("stack\tinput\n");display(stack,top_stack,input,top_input);while(1){

if((stack[top_stack]=='$')&&(input[top_input]=='$'))

Page 51: ++++Imp Compiler c Programs

{printf("string accepted");break;

}if(table[find(stack[top_stack])][find(input[top_input])]==' '){

printf("parse error");getch();exit(0);

}if(table[find(stack[top_stack])][find(input[top_input])]=='<'){

stack[++top_stack]='<';stack[++top_stack]=input[top_input];top_input++;display(stack,top_stack,input,top_input);continue;

}if(table[find(stack[top_stack])][find(input[top_input])]=='>'){

stack[++top_stack]='>';display(stack,top_stack,input,top_input);top_stack-=3;display(stack,top_stack,input,top_input);

}}getch();

}

OUTPUT:

Operator precedence parsing for E->E+E/E*E/a

Page 52: ++++Imp Compiler c Programs

Enter the stringa+a*a

stack input$ a+a*a$$<a +a*a$$<a> +a*a$$ +a*a$$<+ a*a$$<+<a *a$$<+<a> *a$$<+ *a$$<+<* a$$<+<*<a $$<+<*<a> $$<+<* $$<+<*> $$<+ $$<+> $$ $string accepted

Page 53: ++++Imp Compiler c Programs

RESULT: Hence, the given program has been executed and the output has been

verified successfully.

INTERMEDIATE CODE GENERATOR

AIM:

Page 54: ++++Imp Compiler c Programs

To write a C++ program to generate the intermediate code.

ALGORITHM:

1. Start the program.

2. Declare the array and other necessary variables.

3. Define the main function.

4. Get the expression from the user.

5. Scan the expression and put it in array ‘t’.

6. Check the position of 2, 0 & 4 characters is alphabets.

7. Print the expression and MOV R t the character in 2nd position.

8. Else print “Enter the correct expression”.

9. Start switch case for 3rd symbol and follow the steps 10 to

10.If ‘*’ then print MUL character at 4th position with R.

11. Print MOV R to character at position 0.

12.If ‘+’ then print ADD character at 4th position with R.

13. Print MOV R to character at position 0.

14.If ‘-’ then print SUB character at 4th position with R.

15. Print MOV R to character at position 0.

16.If ‘/’ then print DIV character at 4th position with R.

17. Print MOV R to character at position 0.

18. For default case, print “Invalid operator”.

19. End the program.

PROGRAM:

# include<stdio.h>

Page 55: ++++Imp Compiler c Programs

# include<conio.h># include<ctype.h>char s[20],t[20];void main(){

clrscr();printf("Enter the expression: ");scanf("%s",&t);if(isalpha(t[2])&&isalpha(t[0])&&isalpha(t[4])){

printf("Mov%c,R \n",t[2]);}elseprintf("Enter correct exp: ");switch(t[3]){

case '*':printf("MUL%c,R \n",t[4]);printf("MOVR,%c \n",t[0]);break;case '+':printf("ADD%c,R \n",t[4]);printf("MOVR,%c \n",t[0]);break;case '-':printf("SUB%c,R \n",t[4]);printf("MOVR,%c \n",t[0]);break;case '/':printf("DIV%c,R \n",t[4]);printf("MOVR,%c \n",t[0]);break;default:printf("INVALID OPERATOR");break;

}getch();

}

OUTPUT:

Enter the expression: a=b+c

Page 56: ++++Imp Compiler c Programs

Mov b,RADD c,RMOV R,a

Page 57: ++++Imp Compiler c Programs

RESULT: Hence, the given program has been executed and the output has been

verified successfully.

SLR PARSING TABLE CONSTRUCTION

AIM:

Page 58: ++++Imp Compiler c Programs

To write a C++ program to generate a parsing table for SLR Parsing.

ALGORITHM:

1. Start the program.

2. Declare all necessary header files and variables.

3. construct SLR parsing table for all the states and fill the Action and

Goto first.

4. Insert the initial state as 0 in the stack.

5. Compare with the first input symbol.

6. Action is taken according to general parsing table.

7. If action=Shift, goto step 8 else step 9

8. push the symbol in stack.

9. If action= Reduce, pop the symbol from the stack.replace by the non

terminal symbol, else goto step 10.

10. if action=goto, push the state number in the stack.

11. If action= accept, it implies the parsing is successful.

12. end the program.

PROGRAM:

Page 59: ++++Imp Compiler c Programs

#include<iostream.h>#include<conio.h>#include<fstream.h>#include<string.h>#include <cfg.h>void main(){ clrscr(); g.getdfg(); int h[100],count=0,rt=0,found=0; set_of_item cc[20]; str t=putdot (g.p[0],2); cc[0] = closure(t.ele); int tab[20][20]; for(int i=0; i<20; i++) for(int j=0; j<20;j++) tab [i][j] =0; int m=0; count++; char a[20]; int ll=0; for (i=0; i<g.nv;i++) {

a[i]=g.v[i]; } for(j=0; j=g.nt;j++) {

a[i]=g.t[j];i++;a[i]=’$’;i++;a[i]=’\0’;for(i=0; i<count; i++){ m=0; for(j=0; j<g.nv; j++) {

found = 0;set_of_item t=go_to(cc[i],g.v[j]);if(t.c !=0)

{for(int k =0; k<count ; k++)if(cc[k] equals (t) ==1)

{for(int ml=0; ml<strlen (a) ;ml++){

Page 60: ++++Imp Compiler c Programs

m=ml; tab [i] [m] =k; m++;}

} found=1; break;}if (found != 1){ for (int ml=0; ml<strlen (a); ml++) { if (a[ml] == g.v[j];

{ m=ml; tsb [i] [m] = count; m++;}

} cc [count++] =t;}

} } for (j=0; j<g.nt; j++) {

found=0;set_of_item t = go_to(cc [i], g.t[j]);if(t.c != 0){ for(int k=0; k<count ;k++) if(cc [k].equals (t) ==1) {

fpr(int ml=0; ml<strlen(a) ;ml++){ if(a[ml] == g.t [j]) {

m=ml;tab[i] [m] = k;m++;

}}found=1;break;

} if(found !=1) {

Page 61: ++++Imp Compiler c Programs

for(int ml=0;ml<strlen(a); ml++){ if(a[ml] == g.v[j]); {

m=ml;tab[i] [m] =count;m++;

}}cc[count++]=t;

}}

} for(j=0;j<g.nt;j++) {

found=0;set_of_item t=go_to(cc[i],g.t[j]);if(t.c !=0){ for(int ml=0;ml<strlen(a);ml++) {

if(a[ml] ==g.t[j]) { m=ml; tab [i][m] =k; m++;}

} found=1; break;

} if(poped==tab[0][j]) break; } } else { cout<<”not accepted”; getch(); exit(0); }}cout<<”accepted”;getch();}

Page 62: ++++Imp Compiler c Programs

OUTPUT:

IN.DAT

Page 63: ++++Imp Compiler c Programs

357ETF+*()IS = EE = E + TE = TT = T * FT = FF = ( E )F = i

SLR-TABLE

E T F + * ( ) i $0 1 2 3 S4 S51 S62 r2 S7 r2 r23 r4 r4 r4 r44 8 2 3 S4 S55 r6 r6 r6 r66 9 3 S4 S57 10 S4 S58 S6 S119 r1 S7 r1 r110 r3 r3 r3 r311 r5 r5 r5 r5

Page 64: ++++Imp Compiler c Programs

RESULT: Hence, the given program has been executed and the output has been

verified successfully.