Added method output_file_suffix to code generator API.
[voodoo-lang.git] / lib / voodoo / generators / nasm_elf_generator.rb
blobae30e61cf7e59e44217b8e67a24a124aa93a9603
1 require 'voodoo/config'
2 require 'voodoo/generators/command_postprocessor'
4 module Voodoo
5   # Class that generates ELF object files by invoking nasm on
6   # the output of a code generator that generates NASM assembly.
7   class NasmELFGenerator
8     def initialize nasmgenerator, nasm_extra_args
9       @nasmgenerator = nasmgenerator
10       @nasm_extra_args = nasm_extra_args
11       @output_file_suffix = '.o'
12     end
14     include CommandPostProcessor
16     def output_file_name input_name
17       input_name.sub(/\.voo$/, '') + @output_file_suffix
18     end
20     def output_file_suffix
21       @output_file_suffix
22     end
24     # Writes the generated code to the given IO handle
25     def write io
26       # Create temporary file to write NASM code to
27       if io.respond_to? :path
28         base = File.basename(io.path).sub(/([^.]*).*/, "\\1")
29       else
30         base = self.class.name
31       end
32       
33       Tempfile.open(base + '.asm') do |nasmfile|
34         Tempfile.open(base + '.o') do |elffile|
35           elffile.close
36           # Write NASM code to nsamfile
37           @nasmgenerator.write nasmfile
38           nasmfile.close
39           # Find out the name of the nasm executable
40           if ENV.has_key? 'NASM'
41             nasm = ENV['NASM']
42           elsif ENV.has_key? 'YASM'
43             nasm = ENV['YASM']
44           else
45             nasm = Voodoo::Config.nasm_command
46           end
47           # Invoke nasm on nasmfile
48           command = "#{nasm} #{@nasm_extra_args}" +
49             " -o #{shell_encode elffile.path}" +
50             " #{shell_encode nasmfile.path}"
51           if system(command)
52             write_file_to_io elffile.path, io
53           end
54           elffile.unlink
55         end
56         nasmfile.unlink
57       end
58     end
59   end
60 end