0
votes

I want to create a programming language consisting multiple character variables (e.g. abc=10, num=120). I was able to create single character variable . The .y code is :

%{
    #include <stdio.h>
                  //char sym[1000];
    //int x=0;
    int sym[26];

%}


%token NUMBER ADD SUB MUL DIV ABS EOL ID ASS
%%
calclist : 
    | calclist exp EOL   { printf("= %d\n", $2); } 
    | ID ASS exp EOL     { sym[$1] = $3;

             }
;
exp:    factor           { $$=$1; }
    | exp ADD factor     { $$ = $1 + $3; }
    | exp SUB factor     { $$ = $1 - $3; }
;
factor :    term         { $$=$1; }
    | factor MUL term    { $$ = $1 * $3; }
    | factor DIV term    { $$ = $1 / $3; }
;
term :  NUMBER       { $$=$1; }

;

%%
int main(int argc, char **argv)
{
yyparse();
}
yyerror(char *s)
{
fprintf(stderr, "error: %s\n", s);
} 

and the .l code is :

%{
# include "P3.tab.h"
#include <stdio.h>
#include <stdlib.h>
extern int yylval;
//int m=0;
%}

%%
"+"     { return ADD; }
"-"     { return SUB; }
"*"  { return MUL; }
"/"     { return DIV; }
"=" { return ASS; }
[a-z]+  { yylval= *yytext  - 'a' ;  
     return ID ; }
[0-9]+  { yylval = atoi(yytext); return NUMBER; }
\n   { return EOL; }
[ \t]   { /* ignore whitespace */ }
.    { printf("Mystery character %c\n", *yytext); }
%%
int yywrap()
{
return 1;
}

So, with this code , I can only create a=10,x=90 kind of single character variable . How can I create multiple character variable And I also want to check if it is already declared or not ?

1

1 Answers

1
votes

This has very little to do with bison or flex. In fact, your flex patterns already recognise multi-character identifiers (as long as they are purely alphabetic), but the action ignores characters after the first.

What you need is some kind of associative container like a hash table, which you could use as a symbol table instead of the vector sym.

The Bison manual includes a number of small example calculator programs. See, for example, mfcalc, which includesa symbol table implemented as a simple linear association list.