module Voodoo
  # Voodoo compiler driver.
  # The compiler driver reads input from a parser (see
  # Voodoo::Parser), feeds it to a code generator (see
  # Voodoo::CommonCodeGenerator), and writes the generated code.
  #
  # An example of its usage can be found on the main page for the
  # Voodoo module.
  class Compiler
    # Initialize a compiler.
    #
    # Parameters:
    # [parser] the parser to be used (see Voodoo::Parser)
    # [code_generator] the code generator to be used
    #                  (see Voodoo::CommonCodeGenerator)
    # [output] an IO object. The generated code will be written to it
    def initialize parser, code_generator, output
      @parser = parser
      @generator = code_generator
      @output = output
    end

    # Perform the compilation.
    def compile
      section = :code
      while true
        statement = @parser.parse_top_level

        break if statement == nil
        next if statement.empty?

        case statement[0]
        when :section
          section = statement[1]
        when :function
          @generator.add section, [:function, statement[1]] + statement[2]
        else
          @generator.add section, statement
        end
      end

      @generator.write @output
    end
  end
end
