0
votes

I have the following code for lex and yacc. I am getting kind of extra values in the printed statement can anyone tell. whats wrong with the code?

Lex code:

%{
#include <stdio.h>
#include "y.tab.h"
%}

%%
[ \t] ;
[+-]  { yylval=yytext; return Sym;}
(s|c|t)..x  { yylval=yytext; return Str;}
[a-zA-Z]+  { printf("Invalid");}
%%
int yywrap()
{
return 1;
}

yacc code:

%{
#include<stdio.h>
%}

%start exps
%token Sym Str

%% 
exps: exps exp 
    | exp
    ;
exp : Str Sym Str {printf("%s",$1); printf("%s",$2); printf("%s",$3);}
    ;
%%

int main (void) 
{
while(1){
return yyparse();
}
}

yyerror(char *err) {
    fprintf(stderr, "%s\n",err);
}

Input: sinx+cosx

output: sinx+cosx+cosxcosx

look at the output of the code!!!

1
if i am trying to print $1. its printing the whole input sinx+cosxPramodHegde

1 Answers

0
votes

yytext is a pointer into flex's internal scanning buffer, so its contents will be modified when the next token is read. If you want to return it to the parser, you need to make a copy:

[+-]  { yylval=strdup(yytext); return Sym;}
(s|c|t)..x  { yylval=strdup(yytext); return Str;}

Where symbols are a single character, it might make more sense to return that character directly in the scanner:

[-+]  { return *yytext; }

in which case, your yacc rules should use the character directly in '-single quotes:

exp : Str '+' Str {printf("%s + %s",$1, $3); free($1); free($3); }
    | Str '-' Str {printf("%s - %s",$1, $3); free($1); free($3); }