0
votes

I want to make a parser with characters rather than numbers.

Like (a+b)*c. I want to make a rule according to the precedence of each operator. For example, expr + term | It is such a construct that follows the same precedence as term .. and inserts the value of identify at the end.

lex(flex) file:

%{
    #include <stdio.h> 
    #include <stdlib.h>
    #include "y.tab.h"
    #include <ctype.h>
    #include <string>
%}
alpha [a-zA-Z]
%%
{alpha}*        return *yytext;
"+"             return *yytext;
"*"             return *yytext;
[()]            return *yytext;
[ \b\t\n]       ;
%%
int yywrap() { return 1; }
int main() { yylex(); return 0; }

yacc(bison) file:

%{
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    int yyerror();
    int yylex();

%}
%token id
%%

expr : expr '+' term {$$ = $1 + $3;}
    |term            {$$ = $1;}
    ;
term : term '*' factor  {$$ = $1 + $3;}
    |factor             {$$ = $1;}
    ;
factor : '(' expr ')'  {$$ = $2;}
    |id                 {$$ = $1;}
    |id id              {$$ = $1+$2;}
    ;

%%

void yyerror() {
    printf("yyerror\n");

}

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

I honestly don't know what went wrong. I've been studying for three days, but I haven't been able to solve it.

what should I do?

This question is missing an error description. That is, when you compile and run your program what happens and how does it differ from what you want to happen? Does it fail to compile. Does it abort with an error when run? Does it compile and run fine, but give a different result than you want it to? If so, what does it do (on which input) and what do you want it to do?sepp2k
At a glance I can see the following problems with your code: You define and use an id token in your grammar (which btw should be called ID with capital letters according to the usual naming conventions), but never return such a token in your lexer. You also use the semantic values of those id tokens, but never set any semantic values in the lexer. You also don't do anything with the values you calculate in your actions and it is unclear to me what you want your program to actually do. For example if a user enters "a+b*c" as the input, what would you want the output to be?sepp2k
the value I want Input : a*((bc+de)*f) output: abcdef. However, the current value, including yyerror, does not meet expectations. Input : a*((bc+de)*f) output : *+yyerror I want the output of characters and operators with (,) removed. What should I do?kim