Frage

There are 5 rules. I have to check incompatible type in initialization or double declarations. I know that I need in symbol table. I know about $i. And all other stuff. But I don't have any ideas how to implement the code. Sorry for my English, I am not native speaker.

1)prog:
    PROGMY IDENT  ';' decls BEGINMY stats ENDMY '.' ;

2) decl:
    CONSTMY IDENT '=' NUM ';' {} 
  |
     VARMY VARFULL {}
  |
    error ';'  ;

3) VARFULL:
  MYPEREMEN ':' MYTYPE ';' {}  
  |
  VARFULL MYPEREMEN ':' MYTYPE ';' 

4) MYTYPE :
  MYINT      {}   //int
  |
  MYBOOL     {}  //bool
  ;

5)  MYPEREMEN :
  IDENT      {}  
  |
  MYPEREMEN ',' IDENT   {}  

  ;
War es hilfreich?

Lösung 2

Bison uses the following paradigm:

// declarations
%%
non-terminal : rule { c/c++ action }
%%
// your functions

So to elaborate on the previous answer:

prog:
    PROGMY IDENT  ';' decls BEGINMY stats ENDMY '.' 
    { your code; }
    ;   // bison (not C/C++) terminal semi-colon

As a separate note, since parsers are slow you might want to use "inline" for code functions as much as reasonable. The previous comment on what code there is to write is right-on. That is, if you are going to insert a symbol into a symbol table, you need to discover whether the symbol is there, and if not, then insert it.

Andere Tipps

bison executes the semantic action associated with a rule when it reduces the rule. So generally what you do is put code in the action associated with a declaration to check to see if a symbol is already in the symbol table, and then add it to the symbol table. The symbol table itself is a global variable. So you might have a rule like:

declaration: type IDENT {
        if (symbol_exists(symbol_table, $2))
            Error("duplicate symbol %s", $2);
        else
            AddSymbolWithType(symbol_table, $2, $1); }

Alternately, you could put the error check into the function AddSymbolWithType and make your grammar file cleaner.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top