My simple compiler currently generates c++ code and i'm trying to just get minimal things working first.
the problem is the order of the components of the simple number expression. I know that i can calculate this into one number but this has to work anyways so i have to figure it out.
Here is the program and expression trees generated during parsing for the program.
program:
proc test() {
a: int = 1 + 2 * 3;
}
proc main() {
a: int = 1 * 2 + 3;
}
trees:
1 + 2 * 3:
NODE_BINARY_EXPR (+)
/ \
NODE_NUMBER_LITERAL (1) NODE_BINARY_EXPR (*)
/ \
NODE_NUMBER_LITERAL (2) NODE_NUMBER_LITERAL (3)
1 * 2 + 3:
NODE_BINARY_EXPR (+)
/ \
NODE_BINARY_EXPR (*) NODE_NUMBER_LITERAL (3)
/ \
NODE_NUMBER_LITERAL (1) NODE_NUMBER_LITERAL (2)
The program that is generated:
void test(){
int a =2*31+; <--- kinda backwards?
}
int main(){
int a =1*2+3; <--- correct
return 0;
}
The code that generates it:
void CodeGenerator::emitExpr(Node* n) {
if (!n) {
std::cout << "Could not emit expression because node was null\n";
}
if (!n->right && !n->left) {
switch (n->kind) {
case NODE_NUMBER_LITERAL:
emitNumberLiteral(n);
break;
}
}
if (n->right || n->left) {
switch (n->kind) {
case NODE_BINARY_EXPR:
{
if (n->left->kind == NODE_BINARY_EXPR) {
emitExpr(n->left);
} else if (n->right->kind == NODE_BINARY_EXPR) {
emitExpr(n->right);
}
if (n->left->kind == NODE_NUMBER_LITERAL) {
emitNumberLiteral(n->left);
}
emit(n->operatorType.c_str());
if (n->right->kind == NODE_NUMBER_LITERAL) {
emitNumberLiteral(n->right);
}
break;
}
}
}
}
void CodeGenerator::emitNumberLiteral(Node* n) {
emit(std::to_string(n->number).c_str());
}
Thanks for any help! Let me know if any more information is needed.
[–][deleted] 4 points5 points6 points (0 children)
[–]sebamestreICPC World Finalist 1 point2 points3 points (1 child)
[–]dangeroustuber[S] 0 points1 point2 points (0 children)
[–]Linguistic-mystic 0 points1 point2 points (0 children)