Friday, April 16, 2010

Compiler progress - Possible Bytecode API

I have worked on the compiler and I expect to have it reach the point where it is good enough for me to start the next phase: bytecode generation.

At this point, the lexer is also essentially finished, even though it still lacks features such as \xFFFF sequences in strings.

My goal here is not to have them both complete yet, but rather to go forward until it becomes possible to have some useful *tests*.
With a tree available, I can check the document to see if it is valid, while I keep generating code at the same time.

To show what I have in mind for a compiler API, what's better than an example?
//Let's consider a sum operation was found
Variable left = parseExpression(sum.left,
bytecodeManager, tmpVariableManager);
Variable right = parseExpression(sum.right,
bytecodeManager, tmpVariableManager);
Variable output = tmpVariableManager.fetchNew();
bytecodeManager.appendInstruction(
new AddInstruction(output, left, right));
left.releaseIfTemporary();
right.releaseIfTemporary();
return output;
For a while statement, I could do something like
//Let's consider a while operation was found
Label begin = bytecodeGenerator.newLabel();
bytecodeGenerator.assignLabelToNextInstruction(begin);
Variable cond = parseExpression(whileStmt.expr);
Label end = bytecodeGenerator.newLabel();
bytecodeGenerator.appendInstruction(new UnlessInstruction(cond, end));
parseStatement(whileStmt.body, bytecodeManager, tmpVariableManager);
bytecodeGenerator.appendInstruction(new InconditionalJump(begin));
bytecodeGenerator.assignLabelToNextInstruction(end);
I'm not 100% sure about this API and it'll probably change, but I really like it.
First turning a sequence of characters into tokens, then turning the sequence of tokens into a tree and now turning a tree into a list of commands, just so that later I can turn the list of commands into a bytecode binary. That's essentially all a compiler needs to do.
Of course, the compiler is nothing without the virtual machine, so I'll have to look into that too.

No comments:

Post a Comment