~tim/scheme-vm

ref: c5110102ce2df2d78a0c87f293edf20f5a3984e7 scheme-vm/vm/pretty_printer.rb -rw-r--r-- 783 bytes
c5110102Tim Morgan Add more char functions 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
require 'pp'

class VM
  class PrettyPrinter
    def initialize(instructions, grouped: false, ip: false)
      @instructions = instructions.dup.flatten.compact
      @grouped = grouped
      @ip = ip
    end

    def format
      count = 0
      [].tap do |pretty|
        while @instructions.any?
          group = []
          group << count if @ip
          if (instruction = @instructions.shift)
            (name, arity) = VM::INSTRUCTIONS[instruction]
            group << "VM::#{name}"
            arity.times { group << @instructions.shift }
            pretty << group
            count += group.size - 1
          else
            pretty << nil
          end
        end
      end.send(@grouped ? :to_a : :flatten)
    end

    def print
      pp(format)
    end
  end
end