# Test case for the code generator API introduced in 0.5.0

require 'voodoo'

# Instantiate code generator
generator = Voodoo::CodeGenerator.get_generator

generator.instance_eval do
  add :code, [:import, :printf], [:export, :main]

  # Define format string
  add :data, [:align], [:label, :format], [:string, "gcd(%d, %d): %d\n\x00"]

  # Define gcd function
  add :functions, [:align], [:label, :gcd],
      [:function, [:x, :y],
       [:iflt, [:x, :y],
        [[:return, :call, :gcd, :y, :x]]],
       [:let, :m, :mod, :x, :y],
       [:ifeq, [:m, 0],
        [[:return, :y]],
        [[:'tail-call', :gcd, :y, :m]]]]

  # Define main
  add :functions, [:align], [:label, :main]
  add_function [:argv, :argc],
               [:let, :x, :call, :gcd, 11, 7],
               [:call, :printf, :format, 11, 7, :x],
               [:set, :x, :call, :gcd, 7, 11],
               [:call, :printf, :format, 7, 11, :x],
               [:set, :x, :call, :gcd, 33, 27],
               [:call, :printf, :format, 33, 27, :x],
               [:return, 0]
end

# Let code generator determine output file name
outfile = generator.output_file_name 'gcd.voo'
File.open(outfile, 'w') { |file| generator.write file }
