I have created a simple grammar for a language I have decided to call SWL:
grammar swl;
program : 'begin' statement+ 'end';
statement : assign | add | sub | mul | div | print | whilecond | ifcond ;
condition : expr ;
expr : '(' expr ')' | expr 'and' expr | expr 'or' expr | 'not' expr | expr '=' expr | expr '>=' expr | expr '<=' expr | expr '>' expr | expr '<' expr | ID | NUMBER;
assign : 'let' ID 'be' (NUMBER | ID) ;
print : 'print' (NUMBER | ID) ;
add : 'add' (NUMBER | ID) 'to' ID ;
sub : 'sub' (NUMBER | ID) 'to' ID ;
mul : 'mul' (NUMBER | ID) 'to' ID ;
div : 'div' (NUMBER | ID) 'to' ID ;
whilecond : 'while (' condition ') do' statement+ 'stop' ;
ifcond : 'if (' condition ') then' statement+ 'stop' | 'if (' condition ') then' statement+ 'else' statement+ 'stop' ;
ID : [a-z]+ ;
NUMBER : [0-9]+ ;
WS : [ \n\t]+ -> skip;
ErrorChar : . ;
I am a bit in trouble with the ifcond
. Given this SWL program:
begin
if (not(a > 1) or (c <= b)) then
mul 5 to k
stop
end
I am able to get this C++ output:
#include <iostream>
using namespace std;
int main() {
if ( !(a>1) || (c<=b)) {
k *= 5;
}
}
This is great! By the way with the following input:
begin
if (not(a > 1) or (c <= b)) then
mul 5 to k
else
mul 15 to k
stop
end
I have this output:
#include <iostream>
using namespace std;
int main() {
if ( !(a>1) || (c<=b)) {
k *= 5;
k *= 15;
}
}
As you can see the second example is missing the else statement
part. What is wrong? Do I have to change the ifcond
grammar and add another rule/variable? This is the MyListner.cpp
file.
void fixString(string& cond) {
size_t pos = cond.find("and", 0);
if (pos != string::npos) { cond.replace(pos, 3, " && "); }
pos = cond.find("or", 0);
if (pos != string::npos) { cond.replace(pos, 2, " || "); }
pos = cond.find("not", 0);
if (pos != string::npos) { cond.replace(pos, 3, " !"); }
}
void MyListener::enterIfcond(swlParser::IfcondContext *ctx) {
string cond = ctx->condition()->getText();
fixString(cond);
cout << string(indent, ' ') << "if (" << cond << ") {" << endl;
}
void MyListener::exitIfcond(swlParser::IfcondContext *ctx) {
cout << string(indent, ' ') << "}" << endl;
}
My suspect is that the grammar is not good enough and I'd need another variable to call the else part. I don't know how to fix this issue, any idea?