Class: Ruby2Js

Inherits:
SexpProcessor
  • Object
show all
Defined in:
lib/goling/translators/javascript.rb

Constant Summary collapse

VERSION =
'1.3.1'
LINE_LENGTH =
78
BINARY =
[:<=>, :==, :<, :>, :<=, :>=, :-, :+, :*, :/, :%, :<<, :>>, :**]
ASSIGN_NODES =

Nodes that represent assignment and probably need () around them.

TODO: this should be replaced with full precedence support :/

[
 :dasgn,
 :flip2,
 :flip3,
 :lasgn,
 :masgn,
 :attrasgn,
 :op_asgn1,
 :op_asgn2,
 :op_asgn_and,
 :op_asgn_or,
 :return,
 :if, # HACK
]

Instance Method Summary collapse

Constructor Details

#initializeRuby2Js

Returns a new instance of Ruby2Js.



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/goling/translators/javascript.rb', line 30

def initialize
  super
  @indent = "  "
  self.auto_shift_type = true
  self.strict = true
  self.expected = String

  @calls = []

  # self.debug[:defn] = /zsuper/
end

Instance Method Details

#cond_loop(exp, name) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/goling/translators/javascript.rb', line 55

def cond_loop(exp, name)
  cond = process(exp.shift)
  body = process(exp.shift)
  head_controlled = exp.shift

  body = indent(body).chomp if body

  code = []
  if head_controlled then
    code << "#{name}(#{cond}){"
    code << body if body
    code << "}"
  else
    code << "begin"
    code << body if body
    code << "end #{name} #{cond}"
  end
  code.join("\n")
end

#indent(s) ⇒ Object



51
52
53
# File 'lib/goling/translators/javascript.rb', line 51

def indent(s)
  s.to_s.split(/\n/).map{|line| @indent + line}.join("\n")
end

#parenthesize(exp) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/goling/translators/javascript.rb', line 42

def parenthesize exp
  case self.context[1]
  when nil, :scope, :if, :iter, :resbody, :when, :while, :until then
    exp
  else
    "(#{exp})"
  end
end

#process_and(exp) ⇒ Object



75
76
77
# File 'lib/goling/translators/javascript.rb', line 75

def process_and(exp)
  parenthesize "#{process exp.shift} and #{process exp.shift}"
end

#process_arglist(exp) ⇒ Object

custom made node



79
80
81
82
83
84
85
# File 'lib/goling/translators/javascript.rb', line 79

def process_arglist(exp) # custom made node
  code = []
  until exp.empty? do
    code << process(exp.shift)
  end
  code.join ', '
end

#process_args(exp) ⇒ Object



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
# File 'lib/goling/translators/javascript.rb', line 87

def process_args(exp)
  args = []

  until exp.empty? do
    arg = exp.shift
    case arg
    when Symbol then
      args << arg
    when Array then
      case arg.first
      when :block then
        asgns = {}
        arg[1..-1].each do |lasgn|
          asgns[lasgn[1]] = process(lasgn)
        end

        args.each_with_index do |name, index|
          args[index] = asgns[name] if asgns.has_key? name
        end
      else
        raise "unknown arg type #{arg.first.inspect}"
      end
    else
      raise "unknown arg type #{arg.inspect}"
    end
  end

  return "(#{args.join ', '})"
end

#process_array(exp) ⇒ Object



117
118
119
# File 'lib/goling/translators/javascript.rb', line 117

def process_array(exp)
  "[#{process_arglist(exp)}]"
end

#process_attrasgn(exp) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/goling/translators/javascript.rb', line 121

def process_attrasgn(exp)
  receiver = process exp.shift
  name = exp.shift
  args = exp.empty? ? nil : exp.shift

  case name
  when :[]= then
    rhs = process args.pop
    "#{receiver}[#{process(args)}] = #{rhs}"
  else
    name = name.to_s.sub(/=$/, '')
    if args && args != s(:arglist) then
      "#{receiver}.#{name} = #{process(args)}"
    end
  end
end

#process_block(exp) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/goling/translators/javascript.rb', line 138

def process_block(exp)
  result = []
  
  exp << nil if exp.empty?
  until exp.empty? do
    code = exp.shift
    if code.nil? or code.first == :nil then
      result << "# do nothing\n"
    else
      result << process(code)
    end
  end

  result = parenthesize result.join ";\n"
  result += ";\n" unless result.start_with? "("

  return result
end

#process_break(exp) ⇒ Object



157
158
159
160
161
162
163
164
165
# File 'lib/goling/translators/javascript.rb', line 157

def process_break(exp)
  val = exp.empty? ? nil : process(exp.shift)
  # HACK "break" + (val ? " #{val}" : "")
  if val then
    "break #{val}"
  else
    "break"
  end
end

#process_call(exp) ⇒ Object



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
# File 'lib/goling/translators/javascript.rb', line 167

def process_call(exp)
str = exp.inspect
  receiver_node_type = exp.first.nil? ? nil : exp.first.first
  receiver = process exp.shift
  receiver = "(#{receiver})" if ASSIGN_NODES.include? receiver_node_type

  name = exp.shift
  args = []
  raw = []

  # this allows us to do both old and new sexp forms:
  exp.push(*exp.pop[1..-1]) if exp.size == 1 && exp.first.first == :arglist

  @calls.push name

  in_context :arglist do
    until exp.empty? do
      arg_type = exp.first.sexp_type
      e = exp.shift
      raw << e.dup
      arg = process e

      next if arg.empty?

      strip_hash = (arg_type == :hash and
                    not BINARY.include? name and
                    (exp.empty? or exp.first.sexp_type == :splat))
      wrap_arg = Ruby2Ruby::ASSIGN_NODES.include? arg_type

      arg = arg[2..-3] if strip_hash
      arg = "(#{arg})" if wrap_arg

      args << arg
    end
  end
#str+
  case name
  when *BINARY then
    "(#{receiver} #{name} #{args.join(', ')})"
  when :[] then
    receiver ||= "self"
    if raw.size == 1 && raw.first.sexp_type == :lit && raw.first.to_a[1].kind_of?(Symbol)
      "#{receiver}.#{args.first[1..-1]}"
    else
      "#{receiver}[#{args.join(', ')}]"
    end
  when :[]= then
    receiver ||= "self"
    rhs = args.pop
    "#{receiver}[#{args.join(', ')}] = #{rhs}"
  when :"-@" then
    "-#{receiver}"
  when :"+@" then
    "+#{receiver}"
  when :new
    args     = nil                   if args.empty?
    args     = "(#{args.join(',')})" if args
    receiver = "#{receiver}"         if receiver

    "#{name} #{receiver}#{args}"
  when :lambda
    receiver = "#{receiver}."        if receiver

    "#{receiver}function"
  else
    args     = nil                 if args.empty?
    args     = "#{args.join(',')}" if args
    receiver = "#{receiver}."      if receiver

    "#{receiver}#{name}(#{args})"
  end
ensure
  @calls.pop
end

#process_const(exp) ⇒ Object



242
243
244
# File 'lib/goling/translators/javascript.rb', line 242

def process_const(exp)
  exp.shift.to_s
end

#process_defn(exp) ⇒ Object



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
# File 'lib/goling/translators/javascript.rb', line 246

def process_defn(exp)
  type1 = exp[1].first
  type2 = exp[2].first rescue nil

  if type1 == :args and [:ivar, :attrset].include? type2 then
    name = exp.shift
    case type2
    when :ivar then
      exp.clear
      return "attr_reader #{name.inspect}"
    when :attrset then
      exp.clear
      return "attr_writer :#{name.to_s[0..-2]}"
    else
      raise "Unknown defn type: #{exp.inspect}"
    end
  end

  case type1
  when :scope, :args then
    name = exp.shift
    args = process(exp.shift)
    args = "" if args == "()"
    body = []
    until exp.empty? do
      body << indent(process(exp.shift))
    end
    body = body.join("\n")
    return "#{exp.comments}#{name}#{args}{\n#{body}\n}".gsub(/\n\s*\n+/, "\n")
  else
    raise "Unknown defn type: #{type1} for #{exp.inspect}"
  end
end

#process_hash(exp) ⇒ Object



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
# File 'lib/goling/translators/javascript.rb', line 280

def process_hash(exp)
  result = []

  until exp.empty?
    e = exp.shift
    if e.sexp_type == :lit
      lhs = process(e)
      rhs = exp.shift
      t = rhs.first
      rhs = process rhs
      rhs = "(#{rhs})" unless [:lit, :str, :array, :iter].include? t # TODO: verify better!

      result << "\n#{lhs[1..-1]}: #{rhs}"
    else
      lhs = process(e)
      rhs = exp.shift
      t = rhs.first
      rhs = process rhs
      rhs = "(#{rhs})" unless [:lit, :str].include? t # TODO: verify better!

      result << "\n#{lhs}: #{rhs}"
    end
  end

  return "{ #{indent(result.join(', '))} }"
end

#process_iasgn(exp) ⇒ Object



307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/goling/translators/javascript.rb', line 307

def process_iasgn(exp)
  lhs = exp.shift
  if exp.empty? then # part of an masgn
    lhs.to_s
  else
    if lhs.to_s[0] == '@'
      "self.#{lhs.to_s[1..-1]} = #{process exp.shift}"
    else
      "#{lhs} = #{process exp.shift}"
    end
  end
end

#process_if(exp) ⇒ Object



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
# File 'lib/goling/translators/javascript.rb', line 320

def process_if(exp)
  expand = Ruby2Ruby::ASSIGN_NODES.include? exp.first.first
  c = process exp.shift
  t_type = exp.first.sexp_type
  t = process exp.shift
  f_type = exp.first.sexp_type if exp.first
  f = process exp.shift

  c = "(#{c.chomp})" #if c =~ /\n/

  if t then
    #unless expand then
    #  if f then
    #    r = "#{c} ? (#{t}) : (#{f})"
    #    r = nil if r =~ /return/ # HACK - need contextual awareness or something
    #  else
    #    r = "#{t} if #{c}"
    #  end
    #  return r if r and (@indent+r).size < LINE_LENGTH and r !~ /\n/
    #end

    r = "if#{c}{\n#{indent(t)}#{[:block, :while, :if].include?(t_type) ? '':';'}\n"
    r << "}else{\n#{indent(f)}#{[:block, :while, :if].include?(f_type) ? '':';'}\n" if f
    r << "}"

    r
  elsif f
    unless expand then
      r = "#{f} unless #{c}"
      return r if (@indent+r).size < LINE_LENGTH and r !~ /\n/
    end
    "unless #{c} then\n#{indent(f)}\nend"
  else
    # empty if statement, just do it in case of side effects from condition
    "if #{c} then\n#{indent '# do nothing'}\nend"
  end
end

#process_iter(exp) ⇒ Object



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
# File 'lib/goling/translators/javascript.rb', line 358

def process_iter(exp)
  iter = process exp.shift
  args = exp.shift
  args = (args == 0) ? '' : process(args)
  body = exp.empty? ? nil : process(exp.shift)

  b, e = #if iter == "END" then
           [ "{", "}" ]
         #else
        #   [ "do", "end" ]
        # end

  iter.sub!(/\(\)$/, '')

  result = []
  result << "#{iter}(#{args})"
  result << "#{b}"
  result << "\n"
  if body then
    result << indent(body.strip)
    result << "\n"
  end
  result << e
  result.join
end

#process_ivar(exp) ⇒ Object



384
385
386
# File 'lib/goling/translators/javascript.rb', line 384

def process_ivar(exp)
  "this.#{exp.shift.to_s[1..-1]}"
end

#process_lasgn(exp) ⇒ Object



388
389
390
391
392
# File 'lib/goling/translators/javascript.rb', line 388

def process_lasgn(exp)
  s = "#{exp.shift}"
  s += " = #{process exp.shift}" unless exp.empty?
  s
end

#process_lit(exp) ⇒ Object



394
395
396
397
398
399
400
401
402
# File 'lib/goling/translators/javascript.rb', line 394

def process_lit(exp)
  obj = exp.shift
  case obj
  when Range then
    "(#{obj.inspect})"
  else
    obj.inspect
  end
end

#process_lvar(exp) ⇒ Object



404
405
406
# File 'lib/goling/translators/javascript.rb', line 404

def process_lvar(exp)
  exp.shift.to_s
end

#process_masgn(exp) ⇒ Object



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
440
441
442
443
444
# File 'lib/goling/translators/javascript.rb', line 408

def process_masgn(exp)
  lhs = exp.shift
  rhs = exp.empty? ? nil : exp.shift

  case lhs.first
  when :array then
    lhs.shift
    lhs = lhs.map do |l|
      case l.first
      when :masgn then
        "(#{process(l)})"
      else
        process(l)
      end
    end
  when :lasgn then
    lhs = [ splat(lhs.last) ]
  when :splat then
    lhs = [ :"*" ]
  else
    raise "no clue: #{lhs.inspect}"
  end

  if context[1] == :iter and rhs then
    lhs << splat(rhs[1])
    rhs = nil
  end

  unless rhs.nil? then
    t = rhs.first
    rhs = process rhs
    rhs = rhs[1..-2] if t == :array # FIX: bad? I dunno
    return "#{lhs.join(", ")} = #{rhs}"
  else
    return lhs.join(", ")
  end
end

#process_nil(exp) ⇒ Object



446
447
448
# File 'lib/goling/translators/javascript.rb', line 446

def process_nil(exp)
  "null"
end

#process_return(exp) ⇒ Object



450
451
452
453
454
455
456
# File 'lib/goling/translators/javascript.rb', line 450

def process_return(exp)
  if exp.empty? then
    return "return"
  else
    return "return #{process exp.shift}"
  end
end

#process_scope(exp) ⇒ Object



458
459
460
# File 'lib/goling/translators/javascript.rb', line 458

def process_scope(exp)
  exp.empty? ? "" : process(exp.shift)
end

#process_true(exp) ⇒ Object



462
463
464
# File 'lib/goling/translators/javascript.rb', line 462

def process_true(exp)
  "true"
end

#process_until(exp) ⇒ Object



466
467
468
# File 'lib/goling/translators/javascript.rb', line 466

def process_until(exp)
  cond_loop(exp, 'until')
end

#process_while(exp) ⇒ Object



470
471
472
# File 'lib/goling/translators/javascript.rb', line 470

def process_while(exp)
  cond_loop(exp, 'while')
end