class Opal::Nodes::TopNode

Generates code for an entire file, i.e. the base sexp

def add_used_helpers

def add_used_helpers
  compiler.helpers.to_a.each { |h| add_temp "$#{h} = Opal.#{h}" }
end

def add_used_operators

def add_used_operators
  operators = compiler.operator_helpers.to_a
  operators.each do |op|
    name = Nodes::CallNode::OPERATORS[op]
    line "function $rb_#{name}(lhs, rhs) {"
    line "  return (typeof(lhs) === 'number' && typeof(rhs) === 'number') ? lhs #{op} rhs : lhs['$#{op}'](rhs);"
    line '}'
  end
end

def closing

def closing
  if compiler.requirable?
    line "};\n"
  elsif compiler.eval?
    line "})(Opal, self);"
  else
    line "});\n"
  end
end

def compile

def compile
  push version_comment
  in_scope do
    line '"use strict";' if compiler.use_strict?
    body_code = stmt(stmts)
    body_code = [body_code] unless body_code.is_a?(Array)
    if compiler.eval?
      add_temp '$nesting = self.$$is_a_module ? [self] : [self.$$class]'
    else
      add_temp 'self = Opal.top'
      add_temp '$nesting = []'
    end
    add_temp 'nil = Opal.nil'
    add_temp '$$$ = Opal.$$$'
    add_temp '$$ = Opal.$$'
    add_used_helpers
    add_used_operators
    line scope.to_vars
    compile_method_stubs
    compile_irb_vars
    compile_end_construct
    line body_code
  end
  opening
  closing
end

def compile_end_construct

Any special __END__ content in code
def compile_end_construct
  if content = compiler.eof_content
    line 'var $__END__ = Opal.Object.$new();'
    line "$__END__.$read = function() { return #{content.inspect}; };"
  end
end

def compile_irb_vars

def compile_irb_vars
  if compiler.irb?
    line 'if (!Opal.irb_vars) { Opal.irb_vars = {}; }'
  end
end

def compile_method_stubs

def compile_method_stubs
  if compiler.method_missing?
    calls = compiler.method_calls
    stubs = calls.to_a.map { |k| "'$#{k}'" }.join(', ')
    line "Opal.add_stubs([#{stubs}]);" unless stubs.empty?
  end
end

def opening

def opening
  async_prefix = "async " if await_encountered
  if compiler.requirable?
    unshift "Opal.modules[#{Opal::Compiler.module_name(compiler.file).inspect}] = #{async_prefix}function(Opal) {"
  elsif compiler.eval?
    unshift "(#{async_prefix}function(Opal, self) {"
  elsif compiler.esm?
    unshift "export default Opal.queue(#{async_prefix}function(Opal) {"
  else
    unshift "Opal.queue(#{async_prefix}function(Opal) {"
  end
end

def stmts

def stmts
  compiler.returns(body)
end

def version_comment

def version_comment
  "/* Generated by Opal #{Opal::VERSION} */"
end