/media/sda-magnetic/david/Dok-15-2023-11-27/fernuni-hagen/cs-i-ii/old-cs-2-02/sqlquantitycompiler.c


#include <stdio.h>
#include <stdlib.h>

/*
expr ::= expr OR term | term 
term ::= term AND not | not
not ::= NOT not | NOT factor | factor
factor ::= ( expr ) | quantity
*/

/*
expr ::= term expr2 
expr2 ::= OR expr | empty
term ::= not term2
term2 ::= AND term | empty
not ::= not2 factor | factor 
not2 ::= NOT not
factor ::= (expr) | quantity
*/

int expr ();
int expr2 ();
int term ();
int term2 ();
int not ();
int not2 ();
int factor ();

int lexi=0;
char *lexs = "(a&b)|c";

int expr () {
    printf ("SELECT x FROM ( ");
    term ();
    expr2 ();
    printf (" )x ");
}

int expr2 () {
    if (lexs [lexi] == '|') {
        printf ("  UNION ");
        lexi++;
        expr ();
    }
}

int term () {
    printf ("SELECT x FROM ( ");
    not ();
    term2 ();
    printf (" )x ");
}

int term2 () {
    if (lexs [lexi] == '&') {
        printf ("  INTERSECT ");
        lexi++;
        term ();
    }
}

int not () {
    not2 ();
    factor ();
}

int not2 () {
    if (lexs [lexi] == '!') {
        lexi++;
        not ();
    }
}

int factor () {
    if (lexs [lexi] == '(') {
        lexi++;
        expr ();
        if (lexs [lexi] == ')') {
            lexi++;
        }
        else {
            printf ("Error");
            exit (0);
        }
    }
    else if ((lexs [lexi] >= 'a') && (lexs [lexi] <= 'z')) {
        printf (" %c ", lexs[lexi]);
        lexi++;
    }
    else {
        printf ("Error");
        exit (0);
    }
}

int main (void) {
    expr ();
    printf (";\n");
    

}