compiler lab 2010 batch

Upload: patrick-jones

Post on 02-Apr-2018

275 views

Category:

Documents


1 download

TRANSCRIPT

  • 7/27/2019 Compiler Lab 2010 Batch

    1/56

    VELALAR COLLEGE OF ENGINEERING

    AND TECHNOLOGY

    ERODE 12.

    LAB MANUAL

    COMPILER LAB

    1

  • 7/27/2019 Compiler Lab 2010 Batch

    2/56

  • 7/27/2019 Compiler Lab 2010 Batch

    3/56

    INDEX

    S.NO.

    DATE

    TITLE OFEXPERIMENT

    PAGENO.

    REMARKS

    1.IMPLEMENTATION OF TOKEN

    SEPARATION4

    2.IMPLEMENTATION OF

    LEXICAL ANALYSIS

    3.

    IMPLEMENTATION OF

    LEXICAL ANALYSIS USING

    LEX TOOL

    4.

    VALIDITY OF EXPRESSION

    IN PREDECTIVE PARSING

    TABLE

    5.

    IMPLEMENTATION OF

    PREDICTIVE PARSING TABLE

    CONSTRUCTION

    6.IMPLEMENTATION OF SHIFT

    REDUCE PARSING

    7.OPERATOR PRECENDENCE

    PARSING

    8.IMPLEMENTATION OF LR

    PARSING

    9. YACC TOOL WITH SIMPLE

    DESK CALCULATOR

    10.INTERMEDIATE CODE

    GENERATION

    11.IMPLEMENTATION OF CODE

    GENERATION

    3

  • 7/27/2019 Compiler Lab 2010 Batch

    4/56

    Expt. No.: 1.

    IMPLEMENTATION OF TOKEN SEPARATION

    * AIM:

    To write a C program to implement the separation of tokens from a sourceprogram.

    * ALGORITHM:

    1. Start the program.2. The lexical analysis phase of the compiler (first phase of compiler) reads the

    character in the source program one by one.3. It groups them into a stream of tokens.4. Each token represents logically cohesive sequence of characters such as an

    identifier, a keyword, a punctuation character, or an operator like =, +, -,*, /.

    5. The keywords, operators, data types are stored in separate array and they areused for comparing the separated tokens from the source program.

    6. The function sepr() is used to separate the tokens from the source program.7. The function symsrch() is used to search the symbols in the source program.8. The function tknsrch() is used to find the keywords and the datatypes in the

    source program.

    9. The function consep() is for finding the constants in the source program.10. The duplicates of all the above functions return values are eliminated using

    the function elimdup().11. Repeat the steps 5 to 10 until the end of file is encountered.12. Stop the program.

    4

  • 7/27/2019 Compiler Lab 2010 Batch

    5/56

    * PROGRAM:

    #include

    char str[100],token[60][60],symb[100],temp[100],op[100],ss[100],kw[60][60],dt[60][60],var[60][60],con[60][60];char kywrd[12][10]={"include","stdio.h","conio.h","main","getch","clrscr","void","if","printf"};char dttyp[11][10]={"int","char","float","double","long","short","struct","union","void"};char oper[50]={'~','!','^','&','*','/','%','-','+','','='};int k=0,x=0,len,ck,cd,cv,cc;

    void sepr(){

    int i=0,j=0;while(str[i]!='\0'){

    if(!isalpha(str[i]) && str[i]!=' ' && str[i]!='\n' && str[i]!='.' && !isdigit(str[i]))

    symb[x++]=str[i++];else if(str[i]==' ' || str[i]=='\n')

    i++;

    else{while(isalpha(str[i]) || str[i]=='.' || isdigit(str[i]))

    temp[j++]=str[i++];temp[j]='\0';strcpy(token[k++],temp);

    j=0;}

    }len=k-1;

    }

    void symsrch(){

    int i,j=0,k=0,x=0,f;for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    6/56

    break;}

    }if(!f)

    ss[x++]=symb[i];

    }}

    void tknsrch(){

    int i,j,fk=0,fd=0;

    for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    7/56

    for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    8/56

    }

    fprintf(o,"\n\nSPECIAL SYMBOLS\n");for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    9/56

    * OUTPUT:

    * RESULT:

    Thus the C program for the token separation is compiled and executed successfullyand the output is verified.

    9

  • 7/27/2019 Compiler Lab 2010 Batch

    10/56

    Expt. No.: 2.

    IMPLEMENTATION OF LEXICAL ANALYSIS

    * AIM:

    To write a C program to implement the lexical analysis phase of the compiler.

    * ALGORITHM:

    1. Start the program.2. Get the input string from the user.3. Identify whether the expression is valid.4. If the expression is invalid then print it as invalid string and terminate.5. Otherwise separate the variables, operators, constants from the entered

    expressions.6. The variables are then placed in the separate array.7. The identified variables are then replaced with ID followed by the constant

    number to indicate the number of variables in the expressions.8. Print the ID values in the expressions instead of the variable names.9. Print the variable names and its corresponding ID values as symbol table.10. Stop the program.

    10

  • 7/27/2019 Compiler Lab 2010 Batch

    11/56

    * PROGRAM:

    #include#include

    #include#include

    char oper[24][2]={"-","+","=","*","/","&","|","~","","^","%","!","+=","-=","*=","%=","/=","++","--","=","!=","=="};char *op="",buf[8],tmpvar[10],tmpopr[10],varlist[10][10]={""},*mstr;int len,i=0,k,cnt,j, v=0,vl=0,fdup=0,fopr=0,b,ii,c,inval=0;

    int lexi(char *);int valid();

    int main(){

    char *str,*temp;clrscr();

    printf("\nEnter the Expression\n");scanf("%s",mstr);if(valid()==0){

    lexi(mstr);

    printf("\n\nExpression is Valid\n\n");}else{

    printf("\n Invalid Expression ~ brackets");getch();return 0;

    }if(inval==0){

    printf("\n%s\n",op);

    printf("\n\nSYMBOL TABLE\n");

    for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    12/56

    len=strlen(str);while(i

  • 7/27/2019 Compiler Lab 2010 Batch

    13/56

    sprintf(buf,"%c",str[i]);strcat(op,buf);i++;

    }while(!isalpha(str[i])&&!isdigit(str[i])&&str[i]!='('&&str[i]!=')')

    {tmpopr[k]=str[i];k++;i++;

    }tmpopr[k]='\0';

    fopr=0;for (j=0;j

  • 7/27/2019 Compiler Lab 2010 Batch

    14/56

    getch();exit(0);

    }}

    if(mstr[ii]==')')

    {b--;ii++;

    }}return b;

    }

    14

  • 7/27/2019 Compiler Lab 2010 Batch

    15/56

    * OUTPUT:

    * RESULT:

    15

  • 7/27/2019 Compiler Lab 2010 Batch

    16/56

    Thus the C program for the token separation is compiled and executedsuccessfully and the output is verified.Expt. No.: 3.

    IMPLEMENTATION OF LEXICAL ANALYSIS USING

    LEX TOOL

    * AIM:

    To write a C program to implement lexical analysis using LEX tool.

    * ALGORITHM:

    1. Start the program.2. Lex program consists of three parts.

    a. Declaration %%b. Translation rules %%c. Auxilary procedure.

    3. The declaration section includes declaration of variables, maintest, constantsand regular definitions.

    4. Translation rule of lex program are statements of the forma. P1 {action}

    b. P2 {action}c. d. e. Pn {action}

    5. Write a program in the vi editor and save it with .l extension.6. Compile the lex program with lex compiler to produce output file as lex.yy.c.

    eg $ lex filename.l$ cc lex.yy.c -ll

    7. Compile that file with C compiler and verify the output.

    16

  • 7/27/2019 Compiler Lab 2010 Batch

    17/56

    * PROGRAM:

    %{#include

    %}

    digit[0-9]+identifier[a-zA-z][a-zA-z0-9]*%%

    #.* printf("%s is a preprocessor directive",yytext);int |float |double |if |char |goto printf("%s is a keyword\n",yytext);{identifier}\( printf("%s is a funtion\n",yytext);\{ printf("%s block begin \n",yytext);\} printf("%s block end \n",yytext);{identifier}(\[[0-9]*\])? printf("%s is identifier\n",yytext);\".*\" printf("%s is string\n",yytext);

    -{digit} printf("%s is negative number",yytext);"+"?{digit} printf("%s is a positive number",yytext);\; |\( |\) printf("%s is a special operator",yytext);\= printf("%s is assignment operator",yytext);\< |\> |\= printf("%s is a relational operator\n",yytext);%%

    int main(int argc,char *argv[]){

    if(argc>1){

    FILE *fp;fp=fopen(argv[1],"r");if(!fp){

    printf("can't open");exit(0);

    }yyin=fp;

    17

  • 7/27/2019 Compiler Lab 2010 Batch

    18/56

    yylex();}return(0);

    }* OUTPUT:

    * RESULT:

    18

  • 7/27/2019 Compiler Lab 2010 Batch

    19/56

    Thus the above program is compiled and executed successfully using theLEX tool and the sample output is verified.Expt. No.: 4.

    VALIDITY OF EXPRESSION IN PREDECTIVE

    PARSING TABLE

    * AIM:

    To write a C program to implement the predictive parsing algorithm.

    * ALGORITHM:

    1. Input: A string w and a parsing table M for grammar G.

    2. Output: If w is in L(G), a leftmost derivation of w; otherwise, an errorindication.

    3. Method: Initially, the parser is in a configuration in which it has $S on thestack with S, the start symbol of G on the top, and w$ in the input buffer. The

    program that utilizes the predictive parsing table M to produce a parse for theinput.

    set ip to point to the first symbol of w$;repeat

    let X be the top stack symbol and a the symbol pointed to by ip;ifX is a terminal or $ then

    ifX=a thenpop X from the stack and advance ip

    else error()else /* X is a nonterminal */

    ifM[X,a] = XY1Y2.....Ykthen begin

    pop X from the stack;push Yk, Yk-1, ..Y1 onto the stack, with Y1 on top;

    output the production XY1Y2.....Ykend

    else errror()

    until X = $ /* stack is empty */

    19

  • 7/27/2019 Compiler Lab 2010 Batch

    20/56

    * PROGRAM:

    # include

    # include# include# include

    char t[6][5]={"x","+","*","(",")","$"};char nt[5][6]={"E","e","T","t","F"};char tv[5][6][6] = {"Te","0","0","Te","0","0","0","+Te","0","0",

    "a","a","Ft","0","0","Ft","0","0","0","a","*Ft","0","a","a","x","0","0","(E)","0","0"};

    struct stack{

    char item[50][25];int top;

    }st;

    void push(char*);void pop();void disp();char* search(char*,char*);int check_ter(char*);

    char expr[6][10],tbv[25];static char prod[10];

    void main(){

    char item[25];int k,j;static int i=0;clrscr();

    printf("Enter the terminals:\n");for(k=0;k

  • 7/27/2019 Compiler Lab 2010 Batch

    21/56

  • 7/27/2019 Compiler Lab 2010 Batch

    22/56

    st.top=st.top-1;}void push(char *item){

    int j;

    char str[5];for(j=0;j

  • 7/27/2019 Compiler Lab 2010 Batch

    23/56

    }

    void disp(){

    int k;

    for(k=0;k

  • 7/27/2019 Compiler Lab 2010 Batch

    24/56

    * OUTPUT:

    * RESULT:

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

    24

  • 7/27/2019 Compiler Lab 2010 Batch

    25/56

    Expt. No.: 5.

    IMPLEMENTATION OF PREDICTIVE PARSING

    TABLE CONSTRUCTION

    * AIM:

    To write a C program to implement the predictive parsing table construcion.

    * ALGORITHM:

    Input: Grammar G.

    Output:Parsing Table M.

    Method:

    1. For each production A of the grammar, do steps 2 and 3.

    2. For each terminal a in FIRST (), add A to M [A, a].

    3. If is in FIRST (), add A to M [A, b] for each terminal b in

    FOLLOW (A). If is in FIRST () and $ is in FOLLOW (A), add

    A to M [A, $].

    4. Make each undefined entry of M be error.

    25

  • 7/27/2019 Compiler Lab 2010 Batch

    26/56

    * PROGRAM:

    # include# include

    # include# include

    char t[7][5]={"x","+","*","(",")","a","$"};char nt[5][6]={"E","e","T","t","F"};char prod[8][10]={"E->Te","e->+Te","e->a","T->Ft","t->*Ft","t->a","F->(E)","F->x"};

    char first[5][5];char fol[5][5];char tab[5][7][10];

    int check_ter(char);int check(char);

    void main(){

    int i=0,x=0,y=0,l=0,j=0;int m=0,n=0;char s,z;

    int k=0;clrscr();printf("\nEnter the terminals:\n");for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    27/56

    k++;first[x][k]=prod[i][3];}else if (check_ter(prod[i][3])==1){

    y=check(prod[i][3]);strcpy(first[x],first[y]);

    }}/*FOLLOW*/

    fol[0][0]='$';fol[0][1]=prod[6][5];

    for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    28/56

    printf("FOLLOW:\n");for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    29/56

    }}int check_ter(char z){

    int x;

    char r[2];r[0]=z;r[1]='\0';for(x=0;x

  • 7/27/2019 Compiler Lab 2010 Batch

    30/56

    * OUTPUT:

    * RESULT:

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

    30

  • 7/27/2019 Compiler Lab 2010 Batch

    31/56

    Expt. No.: 6.

    IMPLEMENTATION OF SHIFT REDUCE PARSING

    * AIM:

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

    * ALGORITHM:

    1. Start the program.2. Get the input string from the user.3. Push $ onto top of the stack.4. Set ip to point to the first input symbol.5. If there is any production which can be used to reduce the input symbol reduce

    the string otherwise push it to the top of the stack.6. Set ip to point to next input symbol.7. Repeat the above steps until the top of the stack contains the $ and the starting

    symbol. If so, then the string is valid, otherwise the string is invalid, return anerror message.

    8. Stop the program.

    31

  • 7/27/2019 Compiler Lab 2010 Batch

    32/56

    * PROGRAM:

    #include#include

    void pus(char);void reduce();char inp1[5][10]={"E+E","E*E","(E)","a"},stk[50],inpt1[10],stk1[50];int ct=0;void main(){

    int k,len;char inpt[10];clrscr();printf("Enter The Input String\n\n");gets(inpt);printf("\n\n");len=strlen(inpt);inpt[len++]='$';inpt[len]='\0';strcpy(inpt1,inpt);len=strlen(inpt);inpt[len++]='$';inpt[len++]='\0';pus('$');pus(inpt[0]);

    for(k=1;k0)

    {for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    33/56

    }stk[ct++]=inpt;i=0;while(stk[i]!='0' && stk[i]!='\0')

    printf("%c",stk[i++]);

    printf("\t%s\tShift\n",inpt1);}void reduce(){

    int j=0,ct1,i,ct2,t,ct3,true=0;char temp[10],tmp;strcpy(stk1,stk);for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    34/56

    }

    34

  • 7/27/2019 Compiler Lab 2010 Batch

    35/56

    * OUTPUT:

    * RESULT:

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

    35

  • 7/27/2019 Compiler Lab 2010 Batch

    36/56

    Expt. No.: 7.

    IMPLEMENTATION OF OPERATOR PRECENDENCE

    PARSING* AIM:

    To write a C program to implement operator precedence parsing algorithm.

    * ALGORITHM:

    Input: An input string w and a table of precedence relations.

    Output: If w is well formed, a skeletal parse tree, with a placeholder

    nonterminal E labeling all interior nodes; otherwise, an error indication.

    Method: Initially, the stack contains $ and the input buffer the string w$.

    set ip to point to the first symbol of w$;repeat forever

    if$ is on top of the stack and ip points to $ thenreturn

    else begin

    let a be the topmost terminal symbol on the stackand let b be the symbol pointed to by ip;

    ifa b thenrepeat

    pop the stackuntil the top stack terminal is related by

  • 7/27/2019 Compiler Lab 2010 Batch

    37/56

    * PROGRAM:

    #include#include

    #define msize 40struct stack{

    int top;char item[msize];

    }s;

    void main(){

    int i,j,re;char *in;char c1,c2;s.top=-1;clrscr();

    printf("Enter the input language\n");scanf("%s",in);

    printf("\nStack elements\t\tInput\t\tActions\n\n");push(&s,'$');printf("$\t\t\t");for(i=0;in[i];i++)

    printf("%c",in[i]);

    printf("$\tInitial\n");for(i=0;in[i];i++){

    re=check(s.item[s.top],in[i]);if(re==1){

    push(&s,in[i]);for(j=0;j

  • 7/27/2019 Compiler Lab 2010 Batch

    38/56

    printf("pop(%c>%c)\n",s.item[s.top+1],in[i]);while(re==0){

    c1=s.item[s.top];c2=s.item[s.top+1];

    re=check(c1,c2);if(re==1){

    re=check(s.item[s.top],in[i]);if(re==1){

    push(&s,in[i]);for(j=0;j

  • 7/27/2019 Compiler Lab 2010 Batch

    39/56

    printf("\nSUCCESS");else

    printf("\nERROR");getch();

    }

    int check(char st,char ip){

    char id[8]={'+','-','*','i','$','/','(',')'};char pre[8][8]={{'=','>','','=','','=','','>',''},{'>','>','>','=','>','>','0','>'},{'')

    return 0;elsereturn 1;

    }push(ps,x)struct stack *ps;char x;{

    ps->item[++(ps->top)]=x;return;

    }

    pop(ps)struct stack *ps;{

    ps->item[--(ps->top)];return;

    }

    39

  • 7/27/2019 Compiler Lab 2010 Batch

    40/56

    * OUTPUT:

    * RESULT:

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

    40

  • 7/27/2019 Compiler Lab 2010 Batch

    41/56

    Expt. No.: 8.

    IMPLEMENTATION OF LR PARSING

    * AIM:

    To write a C program to implement simple ing algorithm.

    * ALGORITHM:

    Input: An input string w and an LR parsing table with functions action and

    goto for a grammar G.

    Output: If w is in L(G), a bottom up parse for w; otherwise an error

    indication.

    Method: Initially, the parser has s0 on its stack, s0 is the initial state, and w$ in

    the input buffer. The parser then executes the program until accept or erroraction is encountered.

    set ip to point to the first symbol of w$;repeat forever begin

    let s be the state on the top of the stack anda the symbol pointed to by ip;

    ifaction [s, a] = shift sthen begin

    push a then s on the top of the stack;

    advance ip to the next input symbol

    endelse ifaction [s, a] = reduce A then begin

    pop 2*|| symbols off the stack;

    let s be the state now on top of the stack;

    push A then goto [s, A] on top of the stack;

    output the production A

    end

    else ifaction [s, a] = accept thenreturn

    else error()end

    41

  • 7/27/2019 Compiler Lab 2010 Batch

    42/56

    * PROGRAM:

    char stk[10],inp[10],pat[20][20][20],prod[10][10],ipsymb[10];int sp,ip,tp;

    char c,v;int i,k,t;

    void gettable(){

    int i,j,k,n;char c;strcpy(pat[0][0],"s5");strcpy(pat[0][3],"s4");strcpy(pat[0][6],"1");strcpy(pat[0][7],"2");strcpy(pat[0][8],"3");strcpy(pat[1][5],"A"); strcpy(pat[1][1],"s6");strcpy(pat[2][1],"r2");strcpy(pat[2][2],"s7");strcpy(pat[2][4],"r2");strcpy(pat[2][5],"r2");strcpy(pat[3][1],"r4");strcpy(pat[3][2],"r4");strcpy(pat[3][4],"r4");strcpy(pat[3][5],"r4");strcpy(pat[4][0],"s5");strcpy(pat[4][3],"s4");strcpy(pat[4][6],"8");strcpy(pat[4][7],"2");strcpy(pat[4][8],"3");strcpy(pat[5][2],"r6");strcpy(pat[5][1],"r6");strcpy(pat[5][4],"r6");strcpy(pat[5][5],"r6");strcpy(pat[6][0],"s5");strcpy(pat[6][3],"s4");strcpy(pat[6][7],"9");strcpy(pat[6][8],"3");strcpy(pat[7][0],"s5");strcpy(pat[7][3],"s4");strcpy(pat[7][8],"a");

    strcpy(pat[8][1],"s6");strcpy(pat[8][4],"sb");strcpy(pat[9][1],"r1");strcpy(pat[9][2],"s7");strcpy(pat[9][4],"r1");strcpy(pat[9][5],"r1");strcpy(pat[10][1],"r3");strcpy(pat[10][2],"r3");strcpy(pat[10][4],"r3");strcpy(pat[10][5],"r3");strcpy(pat[11][1],"r5");strcpy(pat[11][2],"r5");strcpy(pat[11][4],"r5");strcpy(pat[11][5],"r5");ipsymb[0]='i';ipsymb[1]='+';ipsymb[2]='*';ipsymb[3]='(';ipsymb[4]=')';ipsymb[5]='$';ipsymb[6]='E';ipsymb[7]='T';ipsymb[8]='F';strcpy(prod[0],"E'->E");strcpy(prod[1],"E->E+T");strcpy(prod[2],"E->T");strcpy(prod[3],"T->T*F");strcpy(prod[4],"T->F");

    strcpy(prod[5],"F->(E)");strcpy(prod[6],"F->i");

    }

    int ipnum(char c){

    int i;for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    43/56

    }

    int stknum(char c){

    char t[10];

    int i;if(c

  • 7/27/2019 Compiler Lab 2010 Batch

    44/56

    while(1){

    c=inp[ip];v=stk[sp];k=ipnum(c);

    i=stknum(v);if(pat[i][k][0]=='s')

    shift();else if(pat[i][k][0]=='r')

    reduce();else if(pat[i][k][0]=='A'){

    printf("\n\nVALID...");getch();exit(0);

    }else{

    printf("\n\nINVALID...");getch();exit(0);

    }printf("%s\t\t",stk);q=ip;while(inp[q]!='\0')

    printf("%c",inp[q++]);

    if(pat[i][k][0]=='s')printf("\t\tShift\n");else if(pat[i][k][0]=='r')

    printf("\t\tReduced by %s\n",prod[pat[i][k][1]-48]);}

    }

    44

  • 7/27/2019 Compiler Lab 2010 Batch

    45/56

    * OUTPUT:

    * RESULT:

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

    verified.

    45

  • 7/27/2019 Compiler Lab 2010 Batch

    46/56

    Expt. No.: 9.

    YACC TOOL WITH SIMPLE DESK CALCULATOR

    * AIM:

    To implement simple desk calculator using yacc tool.

    * ALGORITHM:

    Start the program.

    Yacc program consists of three parts namelyo Declarations

    %%o Transition Rule

    %%o Supporting C routines.

    Declaration part consists of two sections, first section contains only includestatements and the second statements contains declaration of the grammartokens.

    Each rule in set of transition rules consists of grammar production andsemantic action. The set of productions are of the form

    o : {semantic action 1}

    | {semantic action 2}..

    | {semantic action n};

    In the third part, error recovery routines are added.

    The program is typed using vi editor, and saved with .y extension.

    It is first compiled with the yacc compiler to produce the C code for Ccompiler (yacc samp.y).

    After that compile that program with C compiler (cc y.tab.c ly standardoutput file of yacc compiler).

    See the output using ./a.out.

    Stop the program.

    46

  • 7/27/2019 Compiler Lab 2010 Batch

    47/56

    * PROGRAM:

    %{#include#include#define YYSTYPE double

    %}%token NUMBER%left '+' '-'%left '*' '/'%right '^'%right UMINUS%%

    lines : lines expr '\n' {printf("%lf",$2);}| lines '\n'|;

    expr : expr '+' expr {$$=$1+$3;}| expr '-' expr {$$=$1-$3;}| expr '*' expr {$$=$1*$3;}| expr '/' expr {if($3!=0) {$$=$1/$3;}else yyerror("divident should be a positive no.\n");

    }| expr '^' expr { int i,sum=1;for(i=1;i

  • 7/27/2019 Compiler Lab 2010 Batch

    48/56

    * OUTPUT:

    * RESULT:

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

    verified.

    48

  • 7/27/2019 Compiler Lab 2010 Batch

    49/56

    Expt. No.: 10.

    IMPLEMENTATION OF INTERMEDIATE CODE

    GENERATION

    * AIM:

    To write a C program to implement the intermediate code for the given set ofinput expressions.

    * ALGORITHM:

    1. Start the program.2. Get the input expression from the user.3. Check the expressions for its validation.

    4. If it is invalid return the error message.5. Otherwise, for each computation store the result in the three address

    statement (store it in temporary variable say t1, t2, etc.,) .6. Assign the final temporary value to the variable in which the result

    has to be stored.7. Stop the program.

    49

  • 7/27/2019 Compiler Lab 2010 Batch

    50/56

    * PROGRAM:

    #include#include#include

    #include#include

    void small();void dove(int );int p[5]={0,1,2,3,4},c=1,i,k,l,m,pi;char sw[5]={'=','-','+','/','*'},j[20],a[5],b[5],ch[2];void main(){

    clrscr();printf("Enter the expression:");scanf("%s",j);printf("\n\n\tThe Intermediate code is:\n");small();

    }void dove(int i){

    a[0]='\0';b[0]='\0';I f(!isdigit(j[i+2]) && !isdigit(j[i-2]))

    {a[0]=j[i-1];

    b[0]=j[i+1];}if(isdigit(j[i+2])){

    a[0]=j[i-1];b[0]='t';b[1]=j[i+2];

    }if(isdigit(j[i-2])){

    b[0]=j[i+1];

    a[0]='t';a[1]=j[i-2];

    b[1]='\0';}if(isdigit(j[i+2]) && isdigit(j[i-2]))

    {a[0]='t';

    b[0]='t';a[1]=j[i-2];

    b[1]=j[i+2];itoa(c,ch,10);

    j[i+2]=j[i-2]=ch[0];}

    50

  • 7/27/2019 Compiler Lab 2010 Batch

    51/56

    if(j[i]=='*')printf("\tt%d=%s*%s\n",c,a,b);

    if(j[i]=='/')printf("\tt%d=%s/%s\n",c,a,b);

    if(j[i]=='+')

    printf("\tt%d=%s+%s\n",c,a,b);if(j[i]=='-')

    printf("\tt%d=%s-%s\n",c,a,b);if(j[i]=='=')

    printf("\t%c=t%d",j[i-1],--c);itoa(c,ch,10);j[i]=ch[0];c++;

    small();}void small(){

    pi=0;l=0;for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    52/56

    * OUTPUT:

    * RESULT:

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

    52

  • 7/27/2019 Compiler Lab 2010 Batch

    53/56

    Expt. No.: 11.

    IMPLEMENTATION OF CODE GENERATION

    * AIM:

    To write a C program to implement the code generation algorithm.

    * ALGORITHM:

    The code generation algorithm takes as input a sequence of three addressstatements constituting a basic block. For each three address statement of the formx := y op z we perform the following actions:

    1. Invoke a function getreg to determine the location L where the result

    of the computation y op z should be stored. L will usually be aregister, but it could also be a memory location. We shall describegetreg shortly.

    2. Consult the address descriptor for y to determine y, (one of) the

    current location(s) of y. prefer the register for y if the value of y is

    currently both in memory and a register. If the value of y is not

    already in L, generate the instruction MOV y , L to place a copy of y

    in L.

    3. Generate the instruction OP z, L where z is a current location of z.

    Again, prefer a register to a memory location if z is in both. Updatethe address descriptor of x to indicate that x is in location L. If L is aregister, update its descriptor to indicate that it contains the value of x,and remove x from all other register descriptors.

    4. If the current values of y and/or z have no next users, are not live onexit from the block, and are in register descriptor to indicate that, afterexecution of x := y op z, those registers no longer will contain yand/or z, respectively.

    53

  • 7/27/2019 Compiler Lab 2010 Batch

    54/56

    * PROGRAM:

    #include#include#include

    char exp[10][10],*ope;int i,j,n,s[10],flag2,flag3,r1,r2;

    void check();void oper();

    void main()

    {clrscr();

    printf("\nEnter the No. of Expressions:\n");scanf("%d",&n);

    printf("\nEnter The Expression (In Three Address Code):\n");for(i=0;i

  • 7/27/2019 Compiler Lab 2010 Batch

    55/56

    void check(){

    for(j=0;j

  • 7/27/2019 Compiler Lab 2010 Batch

    56/56

    * OUTPUT: