require 'erb'

SRC_DIR = "src"
MAX_ARITY = 10

TEMPLATES = %w[
  org/jruby/internal/runtime/methods/DynamicMethod
  org/jruby/internal/runtime/methods/DefaultMethod
  org/jruby/internal/runtime/methods/InterpretedMethod
  org/jruby/ast/ArgsNode
  org/jruby/runtime/DynamicScope
  org/jruby/runtime/Block
  org/jruby/runtime/BlockBody
  org/jruby/runtime/NullBlockBody
]

GENERATED_WARNING = "
////////////////////////////////////////////////////////////////////////////////
// NOTE: THIS FILE IS GENERATED! DO NOT EDIT THIS FILE!
// generated from: <%= file_src %>
// using arities: <%= arities_src %>
////////////////////////////////////////////////////////////////////////////////
"

def n_args_in(n)
  ", " + n_args_in_bare(n) if n > 0
end

def n_args_in_bare(n)
  n_args_array(n, "IRubyObject ")
end

def n_args_out(n)
  ", " + n_args_out_bare(n) if n > 0
end

def n_args_out_bare(n)
  n_args_array(n)
end

def n_args_ary(n)
  ", " + n_args_ary_bare(n)
end

def n_args_ary_bare(n)
  return "IRubyObject.NULL_ARRAY" if n == 0

  "new IRubyObject[] {#{n_args_array(n)}}"
end

def n_args_array(n, arg_prefix="")
  (0..(n-1)).to_a.map { |i| "#{arg_prefix}arg#{i}" }.join(", ")
end

def generate(file_src, arities_src)
  file_template = ERB.new(File.read(file_src))
  file_template.filename = file_src
  arities_template = ERB.new(File.read(arities_src))
  arities_template.filename = arities_src
  arity_range = 0..MAX_ARITY
  generated_arities = ""

  for arity in arity_range do
    generated_arities << arities_template.result(binding)
  end

  generated_warning = ERB.new(GENERATED_WARNING).result(binding)

  file_template.result(binding)
end

def generate_all
  TEMPLATES.map do |name|
    name = "#{SRC_DIR}/" + name
    File.open(name +".java", 'w') do |f|
      f.write(generate(name + ".erb", name + ".arities.erb"))
    end
  end
end

if $0 == __FILE__
  generate_all
end
