Class: LexerKit::IR::Instruction

Inherits:
Object
  • Object
show all
Defined in:
lib/lexer_kit/ir/instruction.rb

Overview

Instruction represents a single VM instruction. Each instruction has an opcode and an optional argument.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opcode, arg = 0) ⇒ Instruction

Returns a new instance of Instruction.

Parameters:

  • opcode (Integer)

    opcode from Opcode module

  • arg (Integer) (defaults to: 0)

    argument (interpretation depends on opcode)



12
13
14
15
# File 'lib/lexer_kit/ir/instruction.rb', line 12

def initialize(opcode, arg = 0)
  @opcode = opcode
  @arg = arg
end

Instance Attribute Details

#argObject (readonly)

Returns the value of attribute arg.



8
9
10
# File 'lib/lexer_kit/ir/instruction.rb', line 8

def arg
  @arg
end

#opcodeObject (readonly)

Returns the value of attribute opcode.



8
9
10
# File 'lib/lexer_kit/ir/instruction.rb', line 8

def opcode
  @opcode
end

Class Method Details

.from_binary(bytes) ⇒ Instruction

Decode from binary

Parameters:

  • bytes (String)

    4 bytes

Returns:



31
32
33
34
35
# File 'lib/lexer_kit/ir/instruction.rb', line 31

def self.from_binary(bytes)
  opcode, a1, a2, a3 = bytes.unpack("C4")
  arg = (a1 << 16) | (a2 << 8) | a3
  new(opcode, arg)
end

Instance Method Details

#==(other) ⇒ Object



45
46
47
# File 'lib/lexer_kit/ir/instruction.rb', line 45

def ==(other)
  other.is_a?(Instruction) && @opcode == other.opcode && @arg == other.arg
end

#inspectObject



41
42
43
# File 'lib/lexer_kit/ir/instruction.rb', line 41

def inspect
  "#<Instruction #{self}>"
end

#to_binaryString

Encode to binary (4 bytes: 1 opcode + 3 arg)

Returns:

  • (String)

    binary representation



19
20
21
22
23
24
25
26
# File 'lib/lexer_kit/ir/instruction.rb', line 19

def to_binary
  [
    @opcode,
    (@arg >> 16) & 0xFF,
    (@arg >> 8) & 0xFF,
    @arg & 0xFF
  ].pack("C4")
end

#to_sObject



37
38
39
# File 'lib/lexer_kit/ir/instruction.rb', line 37

def to_s
  "#{Opcode.name(@opcode)} #{@arg}"
end