GitHub Sale: sign up for any paid plan this week and pay nothing until January 1, 2009!  [ hide ]

public
Description: a ruby-to-pyc compiler
Clone URL: git://github.com/why/unholy.git
unholy / lib / unholy / pyasm.rb
100644 354 lines (327 sloc) 7.522 kb
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
class Pyasm
  OPS = {
    :== => 2
  }
 
  attr_accessor :argc, :nlocals, :stacksize, :flags, :consts, :bytecode,
    :filename, :lineno, :name, :symbols, :stacknow, :varsyms, :jumps, :labels
  def initialize(fname, name = "<module>")
    @argc, @nlocals, @stacksize, @flags, @filename, @lineno, @name, @stack, @nopop =
      0, 0, 1, 0x40, fname, 1, name, [], 0
    @consts = [-1, nil]
    @symbols = [:Kernel]
    @bytecode, @varsyms, @labels, @jumps = [], [], {}, {}
  end
 
  def add_const(obj)
    @consts << obj unless @consts.include? obj
    @consts.index(obj)
  end
  def add_sym(name)
    @symbols << name unless @symbols.include? name
    @symbols.index(name)
  end
  def add_varsym(name)
    @varsyms << name unless @varsyms.include? name
    @varsyms.index(name)
  end
  def stack_push obj, b
    @stack << [obj, b]
    @stacksize = @stack.length if @stack.length > @stacksize
    b
  end
  def dump_stack
    @stack.clear
  end
  def bc *bytes
    @bytecode << bytes
    bytes
  end
  def mark_jump n, bc
    @jumps[n] ||= []
    @jumps[n] << bc
  end
 
  def pop_top; bc 0x01; dump_stack end
  def ret_val; bc 0x53 end
  def build_class; bc 0x59 end
  def store_name(name)
    dump_stack
    bc 0x5a, add_sym(name), 0x0
  end
  def store_attr(name)
    dump_stack
    bc 0x5f, add_sym(name), 0x0
  end
  def load_const(obj)
    stack_push obj, bc(0x64, add_const(obj), 0x0)
  end
  def load_name(name)
    stack_push name, bc(0x65, add_sym(name), 0x0)
  end
  def build_tuple(n)
    @stack.slice! -(n-1), (n-1)
    bc(0x66, n, 0x0)
  end
  def build_list(n)
    @stack.slice! -(n-1), (n-1)
    bc(0x67, n, 0x0)
  end
  def load_attr(name)
    stack_push name, bc(0x69, add_sym(name), 0x0)
  end
  def compare_op(op)
    bc 0x6a, OPS[op], 0x0
  end
  def import_name(name)
    bc 0x6b, add_sym(name), 0x0
  end
  def import_from(name)
    bc 0x6c, add_sym(name), 0x0
  end
  def jump_if_false(n)
    mark_jump n, bc(0x6f, n, 0x0)
  end
  def load_fast(n)
    stack_push Object.new, bc(0x7c, n, 0x0)
  end
  def store_fast(n)
    bc 0x7d, n, 0x0
  end
  def call_func(arity)
    dump_stack
    stack_push Object.new, bc(0x83, arity, 0x0)
  end
  def make_func(arity)
    bc 0x84, arity, 0x0
  end
  def prep_send
    @nopop -= 1 if @nopop > 0
  end
  def label l
    @labels[l] = @bytecode.flatten.length
  end
 
  def import_split(mod)
    mod = mod.to_s
    return [mod[/^(.+?)(\.|$)/, 1].intern, mod.intern]
  end
 
  def getinlinecache ic, dst
  end
  def setinlinecache dst
  end
  def getlocal id
    load_fast id - 2
  end
  def setlocal id
    store_fast id - 2
  end
  def getconstant sym
    load_name(sym)
  end
  def import(mod, inner = nil)
    load_const(-1)
 
    mod_in, mod = import_split(mod)
    if inner
      inner_in, inner = import_split(inner)
      load_const(tuple(inner))
      mod_in = inner_in
    else
      load_const(nil)
    end
 
    import_name(mod)
    import_from(inner) if inner
    store_name(mod_in)
    pop_top if inner
  end
  def from(inner, mod)
    import(inner, mod)
  end
  def kernel_send(meth, *args)
    load_name(:Kernel)
    load_attr(meth)
    args.each do |obj|
      load_const(obj)
    end
    call_func(args.length)
  end
 
  def leave
    load_const(nil) if @stack.empty?
    ret_val
  end
  def newarray size
    build_list size
  end
  def putnil
    load_const(nil)
  end
  def putstring(str)
    str = @filename if str == "<compiled>"
    load_const(str)
  end
  def message(meth, op_argc, blockiseq, op_flag, ic)
    # args = @stack.slice! -op_argc, op_argc
    # bytes = @bytecode.slice! -op_argc, op_argc
 
    argc = op_argc + 1
    receiver, recbytes = @stack[-argc]
    args = @stack[-op_argc, op_argc].map { |o,_| o }
    idx = @bytecode.index { |x| x.object_id == recbytes.object_id }
    bytes = []
    if idx
      bytes = @bytecode.slice! idx..-1
 
      unless receiver
        unpop
        case meth
        when :import
          return import(*args)
        when :from
          return from(*args)
        when :tuple
          return load_const(tuple(*args))
        else
          load_name(:Kernel)
          bytes.shift
        end
      else
        @bytecode << bytes.shift
      end
    elsif op_argc > 0
      idx = @bytecode.index { |x| x.object_id == @stack[-op_argc][1].object_id }
      bytes = @bytecode.slice! idx..-1
    end
 
    load_attr(meth)
    @bytecode += bytes
    call_func(op_argc)
  end
  def unpop
    @nopop = 2
  end
  def pop
    pop_top unless @nopop > 0
  end
  def opt_eq arg
    compare_op :==
  end
  def getglobal sym
    case sym when :$0
      load_const(@filename)
    end
  end
  def defineclass klass, iseq, is_singleton
    define :class, klass, iseq, is_singleton
  end
  def definemethod meth, iseq, is_singleton
    define :method, meth, iseq, is_singleton
  end
  def define type, id, iseq, is_singleton
    c = (type == :class) ? -2 : -1
    receiver, recbytes = @stack[c]
    idx = @bytecode.index { |x| x.object_id == recbytes.object_id }
    bytes = @bytecode.slice! idx..-1
    bytes.shift unless receiver
 
    asm = Pyasm.new(@filename, id.to_s)
    asm.load_iseq iseq
    if type == :class
      load_const(id.to_s)
      if bytes.empty?
        load_const(tuple())
      else
        @bytecode += bytes
        build_tuple(1)
      end
    end
    load_const(asm)
    make_func(0)
    if type == :class
      call_func(0)
      build_class
    else
      @bytecode += bytes
    end
    store_name(id)
 
    # this is a bit redundant, but decompyle requires it
    if type == :method
      unless receiver
        load_name(id)
        load_name(:Kernel)
        store_attr(id)
      end
    end
  end
  def branchunless label
    jump_if_false label
  end
 
  def load_iseq iseq
    iseq = iseq.to_a
    @varsyms += iseq[8].reverse
 
    iseq.last.each do |inst|
      case inst
      when Integer # line no
        nil
      when Symbol
        self.label inst
      when Array
        # p inst
        inst[0] = :message if inst[0] == :send
        self.prep_send
        self.send *inst
      end
    end
  end
  def eval src
    begin
      iseq = VM::InstructionSequence.compile(src)
      load_iseq iseq
    rescue NameError => e
      puts "*** Are you sure you're running Ruby 1.9?"
      throw e
    end
  end
 
  def to_pickle
    # rewrite jumps to use python bytecode ordering
    @jumps.each do |n, jset|
      jset.each do |jump|
        idx = @bytecode.index(jump)
        pos = @bytecode[0,idx].flatten.length
        jump[1] = (@labels[n] - pos) - jump.length
      end
      # @jumps[1] = @labels[n]
    end
 
    f = "c"
    f << [@argc, @nlocals, @stacksize, @flags].pack("LLLL")
 
    # bytecode
    bytes = @bytecode.flatten
    f << "s" << bytes.length.to_plong
    f << bytes.pack("c*")
 
    # constants
    f << "(" << @consts.length.to_plong
    @consts.each do |c|
      f << c.to_pickle
    end
 
    # names
    f << "(" << @symbols.length.to_plong
    @symbols.each do |n|
      f << n.to_pickle
    end
 
    # varnames
    f << "(" << @varsyms.length.to_plong
    @varsyms.each do |n|
      f << n.to_pickle
    end
 
    # freevars
    f << "(" << 0.to_plong
 
    # cellvars
    f << "(" << 0.to_plong
 
    # metadata
    f << @filename.to_pickle
    f << @name.to_pickle
    f << 1.to_plong
    f << "".to_pickle
    f
  end
 
  def compile(fname)
    # dump the bytecode
    File.open(fname, "wb") do |f|
      f << "\xB3\xF2\r\n" # magic number for python 2.5
      f << Time.now.to_i.to_plong
 
      # code object
      f << self.to_pickle
    end
  end
end