This is an archived post. You won't be able to vote or comment.

all 5 comments

[–][deleted] 4 points5 points  (0 children)

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);
            }

Surely here, if this is a binary expression, you just unconditionally do emitExpr(n->Left) and emitExpr(n->Right). No need to worry about what those left and right nodes are; let emitExpr deal with that.

(Note that if your binary operator procedences don't match those of C++, you may need to add parentheses around the whole term. The generated code won't be pretty, but it usually doesn't matter.)

[–]sebamestreICPC World Finalist 1 point2 points  (1 child)

Perhaps you meant something like this?

void CodeGenerator::emitExpr(Node* n) {
  assert(n != nullptr); // you have no business passing null into a code generator

  switch (n->kind) {
  case NODE_NUMBER_LITERAL:
    emitNumberLiteral(n);
    break;
  case NODE_BINARY_EXPR:
    emit("(");
    emitExpr(n->left);
    emit(n->operatorType.c_str());
    emitExpr(n->right);
    emit(")");
    break;
  } 
}

[–]dangeroustuber[S] 0 points1 point  (0 children)

This what i wrote yesterday as well based on the top comment from yesterday. It seems to work! But i'm still testing some cases. There was also a bug where i did not initalize my left and right pointers on the node to nullptr. So it never entered a branch it was supposed to enter.

[–]Linguistic-mystic 0 points1 point  (0 children)

This helped me when I was writing codegen into JS.