Skip to content

Commit

Permalink
language: Add modulo % operator that works on integers
Browse files Browse the repository at this point in the history
  • Loading branch information
daviwil committed Mar 17, 2022
1 parent 0590a43 commit cbcf142
Show file tree
Hide file tree
Showing 6 changed files with 19 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/compiler.c
Expand Up @@ -953,6 +953,9 @@ static void compiler_parse_operator_call(CompilerContext *ctx, Token *call_token
case TokenKindSlash:
compiler_emit_byte(ctx, OP_DIVIDE);
break;
case TokenKindPercent:
compiler_emit_byte(ctx, OP_MODULO);
break;
case TokenKindAnd:
compiler_emit_byte(ctx, OP_AND);
break;
Expand Down
2 changes: 2 additions & 0 deletions src/disasm.c
Expand Up @@ -72,6 +72,8 @@ int mesche_disasm_instr(Chunk *chunk, int offset) {
return mesche_disasm_simple_instr("OP_MULTIPLY", offset);
case OP_DIVIDE:
return mesche_disasm_simple_instr("OP_DIVIDE", offset);
case OP_MODULO:
return mesche_disasm_simple_instr("OP_MODULO", offset);
case OP_NEGATE:
return mesche_disasm_simple_instr("OP_NEGATE", offset);
case OP_AND:
Expand Down
1 change: 1 addition & 0 deletions src/op.h
Expand Up @@ -13,6 +13,7 @@ typedef enum {
OP_SUBTRACT,
OP_MULTIPLY,
OP_DIVIDE,
OP_MODULO,
OP_NEGATE, // TODO: Remove in favor of SUBTRACT!
OP_AND,
OP_OR,
Expand Down
2 changes: 2 additions & 0 deletions src/scanner.c
Expand Up @@ -320,6 +320,8 @@ Token mesche_scanner_next_token(Scanner *scanner) {
return scanner_make_token(scanner, TokenKindStar);
case '/':
return scanner_make_token(scanner, TokenKindSlash);
case '%':
return scanner_make_token(scanner, TokenKindPercent);
case '>': {
if (scanner_peek(scanner) == '=') {
scanner_next_char(scanner);
Expand Down
1 change: 1 addition & 0 deletions src/scanner.h
Expand Up @@ -21,6 +21,7 @@ typedef enum {
TokenKindMinus,
TokenKindStar,
TokenKindSlash,
TokenKindPercent,
TokenKindAnd,
TokenKindOr,
TokenKindNot,
Expand Down
10 changes: 10 additions & 0 deletions src/vm.c
Expand Up @@ -751,6 +751,16 @@ InterpretResult mesche_vm_run(VM *vm) {
case OP_DIVIDE:
BINARY_OP(NUMBER_VAL, IS_NUMBER, AS_NUMBER, /);
break;
case OP_MODULO: {
if (!IS_NUMBER(vm_stack_peek(vm, 0)) || !IS_NUMBER(vm_stack_peek(vm, 1))) {
vm_runtime_error(vm, "Operands must be numbers.");
return INTERPRET_RUNTIME_ERROR;
}
int b = (int)AS_NUMBER(mesche_vm_stack_pop(vm));
int a = (int)AS_NUMBER(mesche_vm_stack_pop(vm));
mesche_vm_stack_push(vm, NUMBER_VAL(a % b));
break;
}
case OP_AND:
BINARY_OP(BOOL_VAL, IS_ANY, AS_BOOL, &&);
break;
Expand Down

0 comments on commit cbcf142

Please sign in to comment.