Unordered result because of an ambiguous grammar using Flex and Bison

56 views Asked by At

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.

1

There are 1 answers

0
Jurgen Vinju On

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