I'm writing a simple recursive descent parser that takes standard input and counts the number of 'a' and 'b' characters. The grammar for this is as follows:
S -> A B '\n'
A -> a A | empty
B -> b B | empty
int lookahead;
int nontermA();
int nontermB();
void match (int terminal){
if (lookahead == terminal){
lookahead = getchar();
} else {
printf("Syntax error at %c\n", lookahead);
exit(0);
}
}
void nontermS(){
int a,b;
switch(lookahead){
default:
a = nontermA();
b = nontermB();
printf("Match! Number of A's is %d and number of B's is %d", a,b);
match('\n');
}
}
int nontermA(){
int countA = 0;
switch(lookahead){
case 'a': match('a'); countA++; nontermA(); break;
case 'A': match('A'); countA++; nontermA(); break;
default: break;
}
return countA;
}
int nontermB(){
int countB = 0;
switch(lookahead){
case 'b': match('b'); countB++; nontermB(); break;
case 'B': match('B'); countB++; nontermB(); break;
default: break;
}
return countB;
}
Basically, if I type in something like "aA", "bB", or "abAB", it should just output the number of a's and b's, but the actual output for my program is just 1 for a and b. I also get a syntax error when I type in "ba", as well as if I input "B".