Postfix '++' & '--' works (prefix & postfix are both tested)

This commit is contained in:
2025-01-09 18:33:10 +11:00
parent 6f16c31f24
commit 14696833fd
6 changed files with 140 additions and 16 deletions

View File

@@ -224,6 +224,63 @@ static unsigned int writeInstructionUnary(Toy_Routine** rt, Toy_AstUnary ast) {
result = 1;
}
else if (ast.flag == TOY_AST_FLAG_POSTFIX_INCREMENT || ast.flag == TOY_AST_FLAG_POSTFIX_DECREMENT) { //NOTE: ditto
//read the var name onto the stack
Toy_String* name = TOY_VALUE_AS_STRING(ast.child->value.value);
EMIT_BYTE(rt, code, TOY_OPCODE_READ);
EMIT_BYTE(rt, code, TOY_VALUE_STRING);
EMIT_BYTE(rt, code, TOY_STRING_NAME);
EMIT_BYTE(rt, code, name->info.length); //store the length (max 255)
emitString(rt, name);
//access the value (postfix++ and postfix--)
EMIT_BYTE(rt, code, TOY_OPCODE_ACCESS);
EMIT_BYTE(rt, code,0);
EMIT_BYTE(rt, code,0);
EMIT_BYTE(rt, code,0);
//read the var name onto the stack (again)
name = TOY_VALUE_AS_STRING(ast.child->value.value);
EMIT_BYTE(rt, code, TOY_OPCODE_READ);
EMIT_BYTE(rt, code, TOY_VALUE_STRING);
EMIT_BYTE(rt, code, TOY_STRING_NAME);
EMIT_BYTE(rt, code, name->info.length); //store the length (max 255)
emitString(rt, name);
//duplicate the var name, then get the value
EMIT_BYTE(rt, code,TOY_OPCODE_DUPLICATE);
EMIT_BYTE(rt, code, TOY_OPCODE_ACCESS); //squeezed
EMIT_BYTE(rt, code,0);
EMIT_BYTE(rt, code,0);
//read the integer '1'
EMIT_BYTE(rt, code, TOY_OPCODE_READ);
EMIT_BYTE(rt, code, TOY_VALUE_INTEGER);
EMIT_BYTE(rt, code, 0);
EMIT_BYTE(rt, code, 0);
EMIT_INT(rt, code, 1);
//add (or subtract) the two values, then assign (pops the second duplicate, and leaves value on the stack)
EMIT_BYTE(rt, code, ast.flag == TOY_AST_FLAG_POSTFIX_INCREMENT ? TOY_OPCODE_ADD : TOY_OPCODE_SUBTRACT);
EMIT_BYTE(rt, code,TOY_OPCODE_ASSIGN); //squeezed
EMIT_BYTE(rt, code,0);
EMIT_BYTE(rt, code,0);
//remove the lingering value (yep, this is UGLY)
EMIT_BYTE(rt, code, TOY_OPCODE_ELIMINATE);
EMIT_BYTE(rt, code,0);
EMIT_BYTE(rt, code,0);
EMIT_BYTE(rt, code,0);
//leaves one value on the stack
result = 1;
}
else {
fprintf(stderr, TOY_CC_ERROR "ERROR: Invalid AST unary flag found\n" TOY_CC_RESET);
exit(-1);