0

I am trying to generate intermediate code using the following grammar, but the output i am getting is as if my parser isn't evaluating the input based on this grammar.

below is my lex.l file:

%{
    #include "y.tab.h"
    extern char yyval;
%}


NUMBER      [0-9]       
ALPHABET    [a-zA-Z]

%%

{NUMBER}+   { strcpy(yylval.str, yytext); return ID; }
{ALPHABET}  { strcpy(yylval.str, yytext); return ID; }
\n;

%%

and this is my yacc.y file:

%{
    #include <stdio.h>
    #include <string.h>


    char result_gen();
    char quadruple_entry(char a[], char b, char c[]);
    void three_address_code();

    int q_index = 0;
    char result[3] = {'t','0','\0'};
    char temp[3];
    char temp2[3];

    struct QuadrupleStructure {
        char arg1[10];
        char op;
        char arg2[10];
        char rslt[3];
    }quadruple[25];

    
 
%}

%union {
    char str[10];
    char symbol;
}

%token <str> ID
%type  <str>    expr 

%left '+' '-'
%left '/' '*'


%%


stmt    :   ID '=' expr  { quadruple_entry($1, '=', $3); }
    ;
expr    :   expr '+' expr { quadruple_entry($1, '+', $3); strcpy($$,temp); printf("add"); }

    |   expr '-' expr { quadruple_entry($1, '-', $3); strcpy($$,temp); printf("sub"); }

    |   expr '/' expr { quadruple_entry($1, '/', $3); strcpy($$,temp); printf("mul");}

    |   expr '*' expr { quadruple_entry($1, '*', $3); strcpy($$,temp); printf("div");}

    |   '(' expr ')'  { strcpy($$,$2); }

    |   ID        { strcpy($$,$1); }

%%


char result_gen() {
    strcpy(temp,result);
    result[1]++;
}

char quadruple_entry(char a[], char b, char c[]) {
    result_gen();

    strcpy(quadruple[q_index].arg1, a);
    quadruple[q_index].op = b;
    strcpy(quadruple[q_index].arg2, c);
    strcpy(quadruple[q_index].rslt, temp);

    q_index++;
}

void three_address_code() {
    int i;
    for(i=0 ; i<q_index ; i++) 
    printf("\n%s := %s %c %s", quadruple[i].rslt, quadruple[i].arg1, quadruple[i].op, quadruple[i].arg2);
}

void yyerror(char *s) {
    printf("Error %s, s");
}

int yywrap() {
    return 1;
}

int main() {
    yyparse();
    three_address_code();
    return 0;
} 

The input I entered :

a=(b+c)-10

Output:

=(

Though the expected output was something similar to intermediate code.

My concepts on YACC aren't very strong, so apology beforehand of the silly mistakes. It'd be very helpful if someone can help me figure out what I am doing wrong

  • `=(` is not a valid token for your lexer, so it errors out when it sees that. – Siguza Dec 27 '20 at 00:30
  • @Siguza so i added this to my lex file to recognize those tokens: . { return yytext[0]; } and voila!, it worked like a charm. Thank you so much for your kind help, I am very glad you answered :) – Hamza Hussain Dec 27 '20 at 00:45

0 Answers0