Skip to content

Commit c649ac9

Browse files
committed
[vm] Add dup instructions.
`Dup` will duplicate the value at the top of the stack, while `DupN` will duplicate the top `n` values on the stack.
1 parent cb8ee68 commit c649ac9

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

BYTECODE_REFERENCE.md

+2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ Myst bytecode is a binary stream of instructions for the Myst Virtual Machine to
1212
| | setlocal | 0x02 | name | value | |
1313
| stack | push | 0x10 | value | | value |
1414
| | pop | 0x11 | | value | |
15+
| | dup | 0x12 | | val | val,val |
16+
| | dupn | 0x13 | n | *n | *n,*n |
1517
| math | add | 0x20 | | b,a | a+b |
1618
| | subtract | 0x21 | | b,a | a-b |
1719
| | multiply | 0x22 | | b,a | a*b |

src/bytecode_generator.cr

+12-2
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,20 @@ require "./myst/vm"
33
include Myst::VM
44

55
iseq = InstructionSequence.new
6-
iseq.add_instruction(Instruction::Push.new(MTValue.new("Hello,")))
7-
iseq.add_instruction(Instruction::Push.new(MTValue.new(" world!")))
6+
iseq.add_instruction(Instruction::Push.new(MTValue.new(1_i64)))
7+
iseq.add_instruction(Instruction::SetLocal.new(MTValue.new("n_2")))
8+
iseq.add_instruction(Instruction::Push.new(MTValue.new(1_i64)))
9+
iseq.add_instruction(Instruction::SetLocal.new(MTValue.new("n_1")))
10+
iseq.add_instruction(Instruction::Label.new(MTValue.new("loop")))
11+
iseq.add_instruction(Instruction::GetLocal.new(MTValue.new("n_1")))
12+
iseq.add_instruction(Instruction::GetLocal.new(MTValue.new("n_2")))
813
iseq.add_instruction(Instruction::Add.new)
14+
iseq.add_instruction(Instruction::Dup.new)
915
iseq.add_instruction(Instruction::Write.new)
16+
iseq.add_instruction(Instruction::GetLocal.new(MTValue.new("n_1")))
17+
iseq.add_instruction(Instruction::SetLocal.new(MTValue.new("n_2")))
18+
iseq.add_instruction(Instruction::SetLocal.new(MTValue.new("n_1")))
19+
iseq.add_instruction(Instruction::Jump.new(MTValue.new("loop")))
1020

1121
File.open("./generated_bytecode.mtc", "w") do |io|
1222
iseq.to_bytecode(io)

src/myst/vm/instruction.cr

+3
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ module Myst
1515
def_instruction Push, 0x10,
1616
value : MTValue
1717
def_instruction Pop, 0x11
18+
def_instruction Dup, 0x12
19+
def_instruction DupN, 0x13,
20+
size : MTValue
1821

1922
# Math
2023
def_instruction Add, 0x20

0 commit comments

Comments
 (0)