Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Lex program for implementing three address code

Program:

%{

#include <stdio.h>

#include <stdlib.h>

int temp_count = 1;

%}

DIGIT [0-9]

IDENTIFIER [a-zA-Z_][a-zA-Z0-9_]*

WS [ \t\n]+

%%

{WS} /* Ignore whitespace */

{DIGIT}+ { printf("t%d = %s\n", temp_count++, yytext); }

{IDENTIFIER} { printf("t%d = %s\n", temp_count++, yytext); }

"+" { printf("t%d = t%d + t%d\n", temp_count, temp_count - 1, temp_count - 2);


temp_count++; }

"-" { printf("t%d = t%d - t%d\n", temp_count, temp_count - 1, temp_count - 2);


temp_count++; }

"*" { printf("t%d = t%d * t%d\n", temp_count, temp_count - 1, temp_count - 2);


temp_count++; }

"/" { printf("t%d = t%d / t%d\n", temp_count, temp_count - 1, temp_count - 2);


temp_count++; }

. { printf("Invalid input: %s\n", yytext); }

%%

int yywrap(void) {

return 1; // Indicate that there is no more input


}

int main() {

char input_buffer[1024];

printf("Enter an arithmetic expression: ");

while (fgets(input_buffer, sizeof(input_buffer), stdin)) {

temp_count = 1;

// Pass the input buffer to the lexer

yy_scan_string(input_buffer);

// Call the lexer

yylex();

printf("Enter another arithmetic expression (or press Ctrl+D to exit): ");

return 0;

Output:
mgm14@MGM14 ~ % cd Desktop

mgm14@MGM14 Desktop % cd Sawani

mgm14@MGM14 Sawani % flex address.l

mgm14@MGM14 Sawani % gcc lex.yy.c

mgm14@MGM14 Sawani % ./a.out

Enter an arithmetic expression: g+j=s

t1 = g

t2 = t1 + t0

t3 = j

Invalid input: =

t4 = s

Enter another arithmetic expression (or press Ctrl+D to exit): 2+12=7

t1 = 2
t2 = t1 + t0

t3 = 12

Invalid input: =

t4 = 7

Enter another arithmetic expression (or press Ctrl+D to exit): %

You might also like