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
why (author)
Thu May 15 08:11:54 -0700 2008
commit  ea44e7aaf62d17574d85407d85af286c9879c366
tree    56d106053b97094ba516f5f5e42ecea507d17502
parent  12d52c4ce7154d3cd8300be129d15ed7e57e8b1e
unholy / lib / unholy / pyasm.rb
100644 439 lines (406 sloc) 9.431 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
class Pyasm
  CO_NEWLOCALS = 0x02
  CO_NOFREE = 0x40
 
  VM_CALL_FCALL_BIT = 0x08
 
  OPS = {
    :== => 2
  }
 
  attr_accessor :argc, :stacksize, :flags, :consts, :bytecode,
    :filename, :lineno, :name, :symbols, :stacknow, :varsyms, :jumps, :labels, :lines
  def initialize(fname, type = nil, name = "<module>", lineno = 0, argc = 0)
    @argc, @stacksize, @flags, @filename, @lineno, @name, @stack, @nopop, @type =
      argc, 1, CO_NOFREE, fname, lineno, name, [], 0, type
    @flags |= CO_NEWLOCALS if [:class, :method].include?(type)
    @consts = [-1, nil]
    @symbols = [:Kernel]
    @bytecode, @varsyms, @labels, @lines, @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 infix i
    add = bc i
    @stack.pop
    add
  end
  def binary_add; infix 0x17 end
  def binary_subscr; infix 0x19 end
  def inplace_add; infix 0x37 end
  def print_item; dump_stack; bc 0x47 end
  def print_newline; dump_stack; bc 0x48 end
  def load_locals; bc 0x52 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) if n > 0
    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(n)
    mark_jump n, bc(0x6e, n, 0x0)
  end
  def jump_if_false(n)
    mark_jump n, bc(0x6f, n, 0x0)
  end
  def load_fast(n)
    stack_push n, bc(0x7c, n, 0x0)
  end
  def store_fast(n)
    dump_stack
    bc 0x7d, n, 0x0
  end
  def call_func(arity)
    (arity + 2).times { @stack.pop }
    stack_push Object.new, bc(0x83, arity, 0x0)
  end
  def make_func(arity)
    bc 0x84, arity, 0x0
  end
  def line n
    @lines << [n, @bytecode.flatten.length]
  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 getdynamic id, lvl
    load_name @varsyms[id - 1]
  end
  def getconstant sym
    load_name(sym)
  end
  def print_obj
    print_item
    print_newline
  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
    if @type == :class
      load_locals
    else
      load_const(nil) if @stack.empty?
    end
    ret_val
  end
  def duparray ary
    ary.each do |x|
      load_const x
    end
    build_list ary.length
  end
  def newarray size
    build_list size
  end
  def opt_aref
    binary_subscr
  end
  def opt_ltlt
    build_list 1
    inplace_add
  end
  def opt_plus
    binary_add
  end
  def putnil
    load_const(nil)
  end
  def putstring(str)
    str = @filename if str == "<compiled>"
    load_const(str)
  end
  def putobject(obj)
    load_const(obj)
  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 :print
          @bytecode += bytes
          return print_obj
        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
 
    if meth != :new
      load_attr(meth)
    end
    @bytecode += bytes
 
    if blockiseq
      blk = Pyasm.new(@filename, :block, "<block>", @lines.last[0])
      blk.load_iseq blockiseq
      load_const(blk)
      op_argc += 1
    end
 
    call_func(op_argc)
  end
  def unpop
    @nopop = 2
  end
  def pop
    pop_top unless @nopop > 0 or @stack.empty?
  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
 
    argc = iseq[4][:arg_size]
    argc += 1 if type == :method # python's self
    asm = Pyasm.new(@filename, type, id.to_s, @lines.last[0], argc)
    if type == :class
      asm.load_name(:__name__)
      asm.store_name(:__module__)
    end
    asm.load_iseq iseq
    if type == :class
      load_const(id.to_s)
      if bytes.empty? or @consts[bytes[0][1]].nil?
        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
      if @type == nil
        unless receiver
          load_name(id)
          load_name(:Kernel)
          store_attr(id)
        end
      elsif @type == :class and id == :initialize
        load_name(id)
        store_name(:__init__)
      end
    end
  end
  def branchunless label
    jump_if_false label
  end
 
  def load_iseq iseq
    iseq = iseq.to_a
    @varsyms += iseq[8].reverse
 
    iseq[11].each do |inst|
      case inst
      when Integer # line no
        line inst
      when Symbol
        label inst
      when Array
        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, @varsyms.length, @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
 
    lnotab = ""
    lastn, lastpos = @lines[0]
    @lines[1..-1].each do |n, pos|
      lnotab << [pos - lastpos, n - lastn].pack("cc")
      lastn, lastpos = n, pos
    end
    f << lnotab.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