0

I'm trying to create a section for variable declaration (a bit similar to HTML) using Flex and Bison, my grammar is correct (no lexical or syntax errors), but the displayed result isn't ordered.

example.txt:

    <SUB VARIABLE>
        < a AS INT />;
        <string AS STR />; 
        < x | y AS FLT />;
        <bool AS BOL />; 
        <char AS CHR />; 
    </SUB VARIABLE>
    

the result I get (the incorrect one):

a ---> 1
x ---> 2
y ---> 2
string ---> 4
char ---> 3
bool ---> 5

the result I want to display (the correct one):

a ---> 1
string ---> 4
x ---> 2
y ---> 2
bool ---> 5
char ---> 3

Here's my code:

synt.y:

DECLARATION:    DECLARATION     '<' SUB VARIABLE '>'    SUITE  
            
            |
;


SUITE: '<' idf  SUITE_VAR {inserer($2,getType());}
            | '<' '/' SUB VARIABLE '>' 
;

SUITE_VAR:      '|' idf  SUITE_VAR {inserer($2, getType());}
            |   AS INT '/' '>' ';' SUITE {setType(1);}
            |   AS FLT '/' '>' ';' SUITE {setType(2);}
            |   AS CHR '/' '>' ';' SUITE {setType(3);}
            |   AS STR '/' '>' ';' SUITE {setType(4);}
            |   AS BOL '/' '>' ';' SUITE {setType(5);}
;


My grammar may be ambiguous, I tried many other grammars but I had the same problem. Could you please tell me how I should write my grammar to have an ordered result? Thanks a lot.

lili
  • 1
  • 1
  • If your grammar were ambiguous, bison would report parsing conflicts. An ambiguous grammar cannot produce a parser without conflicts. – rici Apr 16 '22 at 07:54
  • That's true. Even if the result is incorrect, I didn't have warnings nor conflicts. I want to list the variables in order, could you please help me know my mistake in this grammar ? – lili Apr 16 '22 at 07:58
  • Think about how your semantic actions work. Remember that an action is executed (logically) at the end of the input matched, which means that the actions for all contained non-terminals have already been executed. The result is that left-recursive rules evaluate left-to-right, while right-recursive rules evaluate right-to-left. Right-recursive grammars are almost never correct, particularly if rules have side effects. (But you should prefer rules without side-effects, which return a semantic value by setting `$$`.) – rici Apr 16 '22 at 18:01
  • Anyway, your grammar is a mess, perhaps because you were trying to force it to satisfy top-down restrictions. Bison generates bottom-up grammars; you can freely use left-recursion and there's no need for left-factoring. So you can write grammars in a more natural style. – rici Apr 16 '22 at 18:06

1 Answers1

-1

This is not a mistake in your grammar. It's the semantics of the inserer function where you probably have an issue.

Jurgen Vinju
  • 6,393
  • 1
  • 15
  • 26