100% found this document useful (1 vote)
2K views6 pages

Generate Three Address Codes For A Simple Program Using Lex and Yacc .

This document provides code for a simple program that uses Lex and Yacc to generate three address codes. The Lex part defines tokens for numbers and characters. The Yacc part defines expression grammar rules and uses the gencode function to generate three address codes for expressions like t1 = a + b by printing statements like t1 = + a b.

Uploaded by

privateashik2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
2K views6 pages

Generate Three Address Codes For A Simple Program Using Lex and Yacc .

This document provides code for a simple program that uses Lex and Yacc to generate three address codes. The Lex part defines tokens for numbers and characters. The Yacc part defines expression grammar rules and uses the gencode function to generate three address codes for expressions like t1 = a + b by printing statements like t1 = + a b.

Uploaded by

privateashik2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

/*GENERATE THREE ADDRESS CODES FOR A SIMPLE

PROGRAM USING LEX AND YACC .*/

PROGRAM:

LEX PART:

%{

#include<stdio.h>

#include"y.tab.h"

int k=1;

%}

%%

[0-9]+ {

yylval.dval=yytext[0];

return NUM;

\n {return 0;}

. {return yytext[0];}

%%

void yyerror(char* str)

{
printf("\n%s",str);

char *gencode(char word[],char first,char op,char second)

char temp[10];

sprintf(temp,"%d",k);

strcat(word,temp);

k++;

printf("%s = %c %c %c\n",word,first,op,second);

return word; //Returns variable name like t1,t2,t3... properly

int yywrap()

return 1;

main()

yyparse();

return 0;

}
YACC PART:

%{

#include<stdio.h>

int aaa;

%}

%union{

char dval;

%token <dval> NUM

%type <dval> E

%left '+' '-'

%left '*' '/' '%'

%%

statement : E {printf("\nt = %c \n",$1);}

E : E '+' E

char word[]="t";

char *test=gencode(word,$1,'+',$3);

$$=test;

| E '-' E
{

char word[]="t";

char *test=gencode(word,$1,'-',$3);

$$=test;

| E '%' E

char word[]="t";

char *test=gencode(word,$1,'%',$3);

$$=test;

| E '*' E

char word[]="t";

char *test=gencode(word,$1,'*',$3);

$$=test;

| E '/' E

char word[]="t";

char *test=gencode(word,$1,'/',$3);

$$=test;
}

| '(' E ')'

$$=$2;

| NUM

$$=$1;

%%
OUTPUT:

You might also like