Class: Akaza::Ruby2ws::Transpiler

Inherits:
Object
  • Object
show all
Defined in:
lib/akaza/ruby2ws.rb

Instance Method Summary collapse

Constructor Details

#initialize(ruby_code, path:) ⇒ Transpiler

Returns a new instance of Transpiler.

Parameters:

  • ruby_code (String)
  • path (String)

    For debug information



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
# File 'lib/akaza/ruby2ws.rb', line 154

def initialize(ruby_code, path:)
  @ruby_code = ruby_code
  @path = path

  @variable_addr_index = 2
  @variable_addrs = {}

  @label_index = 0
  @labels = {}

  # Method list to compile
  # Array<Array<Command>>
  @methods = []

  # For lazy compiling method.
  # MethodDefinition is inserted to it on :DEFN node.
  # The definition is compiled on call node, such as :CALL.
  # Hash{Symbol => Array<MethodDefinition>}
  @method_definitions = {}

  @method_table = {
    Array: [:size, :push, :pop, :[], :[]=],
    Integer: [:<=>],
    Hash: [:[], :[]=],
  }

  @lvars_stack = []

  @current_class = nil
end

Instance Method Details

#transpileObject



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
# File 'lib/akaza/ruby2ws.rb', line 185

def transpile
  commands = []
  # define built-in functions
  define_array_size
  define_array_pop
  define_array_push
  define_array_ref
  define_array_attr_asgn
  define_hash_ref
  define_hash_attr_asgn
  define_op_spaceship

  # Prelude
  commands.concat compile_expr(PRELUDE_AST)

  ast = RubyVM::AbstractSyntaxTree.parse(@ruby_code)
  body = compile_expr(ast)

  # Save self for top level
  commands << [:stack_push, variable_name_to_addr(:self)]
  commands << [:stack_push, NONE]
  commands << [:heap_save]

  # Reserve heaps for local variables
  commands << [:stack_push, HEAP_COUNT_ADDR]
  commands << [:stack_push, @variable_addr_index + 1]
  commands << [:heap_save]

  commands.concat body
  commands << [:flow_exit]
  commands.concat(*@methods)
  commands_to_ws(commands)
end