'How to write this grammar rule as C code?
I'm creating a parser by hand for a class in my undergrad studies, and I need to convert this first grammar rule into C code. I've gotten the last three, as shown below
1. Declarations -> Var_decl || Declarations Var_decl
2. Var_decl -> TYPE varList SEMI
3. varList -> var || varList COMMA var
4. var -> IDENT || IDENT RBRAK INT_LIT LBRAK
int parse_var(){
struct token t = peek();
if(t.tokenNum == IDENT)
{
consume(IDENT);
t = peek();
//Check if the IDENT has [INT_LIT] after it, making it a single dimension array
if(t.tokenNum == RBRAK)
{
consume(RBRAK);
t = peek();
//Check if the [ has an INT_LIT] after it
if(t.tokenNum == INT_LIT)
{
consume(INT_LIT);
t = peek();
//check for the ]
if(t.tokenNum == LBRAK)
{
consume(LBRAK);
return 0;
}//error handling for missing ']'
fprintf(stderr, "Parsing error: Expected a ']' after the Integer Literal on line %d", t.lineNum);
}//error handling for missing 'INT_LIT'
fprintf(stderr, "Parsing error: Expected an Integer Literal after '[' on line %d", t.lineNum);
return -1;
}
return 0;
}//Error handling for missing Identifier
fprintf(stderr, "Parsing error: Expected an Identifier near text %s on line %d", t.lexeme, t.lineNum);
return -1;
}
/* Helper: consumes a comma separated list of variables
* ex: x, y, z[5]
* returns: -1 upon failure and 0 upon success
*/
int parse_varList()
{
int result = parse_var();
struct token t = peek();
if(t.tokenNum == COMMA)
{
consume(COMMA);
result = parse_varList();
}
return result;
}
int parse_varDeclarations(){
int result = parse_type();
if(result == 0) {
result = parse_varList();
consume(SEMI);
}
return result;
}
Any guidance would be awesome as it's been difficult finding this answer online. I think I could do something similar to how I've done the varList function, but I'm not sure if I'm even on the right track.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
