Class: JvmBytecode::Attributes::Code

Inherits:
Attribute
  • Object
show all
Defined in:
lib/jvm_bytecode/attributes/code.rb

Instance Attribute Summary

Attributes inherited from Attribute

#cp

Instance Method Summary collapse

Methods inherited from Attribute

#bytecode, decode_serial, define, fetch, locatable_at

Constructor Details

#initialize(cp) ⇒ Code

Returns a new instance of Code.



12
13
14
15
16
17
18
# File 'lib/jvm_bytecode/attributes/code.rb', line 12

def initialize(cp)
  super(cp)

  @max_stack = 0
  @max_locals = 0
  @instructions = []
end

Instance Method Details

#additional_bytecodeObject



28
29
30
31
# File 'lib/jvm_bytecode/attributes/code.rb', line 28

def additional_bytecode
  code = @instructions.map(&:bytecode).join('')
  [@max_stack, @max_locals, code.length].pack('S>2I>') + code + [0, 0].pack('S>2')
end

#decode(io) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/jvm_bytecode/attributes/code.rb', line 33

def decode(io)
  io.read(4) # discard length

  @max_stack, @max_locals, len = io.read(8).unpack('S>2I>')
  
  @instructions.clear
  while len > 0
    opcode = io.read(1).unpack('C').first
    inst = Instructions::Instruction.fetch(opcode)
    @instructions << inst.new(cp).tap { |i| i.decode(io) }

    len -= inst.size
  end

  io.read(4) # discard exceptions and attributes
end

#max_locals(n) ⇒ Object



24
25
26
# File 'lib/jvm_bytecode/attributes/code.rb', line 24

def max_locals(n)
  @max_locals = n
end

#max_stack(n) ⇒ Object



20
21
22
# File 'lib/jvm_bytecode/attributes/code.rb', line 20

def max_stack(n)
  @max_stack = n
end

#to_hashObject



50
51
52
53
54
55
56
57
# File 'lib/jvm_bytecode/attributes/code.rb', line 50

def to_hash
  {
    type: self.class.name.split('::').last,
    max_stack: @max_stack,
    max_local_variables: @max_locals,
    instructions: @instructions.map(&:to_hash)
  }
end