Initial commit.
[voodoo-lang.git] / src / compiler.rb
blob3868ed16ac8dd7f29599f54543cd175ed69d6c76
1 class Compiler
2   def initialize parser, code_generator, output
3     @parser = parser
4     @generator = code_generator
5     @output = output
6   end
8   def compile
9     while true
10       words = @parser.parse_line
11       break if words == nil
12       next if words.empty?
13   
14       # Process labels
15       while words[0] =~ /^\w+:$/
16         label = words[0][0..-2]
17         @generator.label label
18         words = words[1..-1]
19       end
20       next if words.empty?
22       # Process code
23       action, args = words[0], words[1..-1]
24       case action
25       when 'call'
26         @generator.call *args
27       when 'else'
28         if words.length == 1
29           @generator.ifelse
30         else
31           if words[1] == 'if'
32             @generator.ifelse
33             @generator.ifnonzero words[2..-1]
34           else
35             raise "Invalid action: #{action} #{words[1]}"
36           end
37         end
38       when 'end'
39         case words[1]
40         when 'function'
41           @generator.end_function
42         when 'if'
43           @generator.end_if
44         else
45           raise "Unknown action: #{action} #{words[1]}"
46         end
47       when 'export'
48         @generator.export *args
49       when 'function'
50         @generator.function args
51       when 'goto'
52         @generator.goto *args
53       when 'if'
54         @generator.ifnonzero *args
55       when 'import'
56         @generator.import *args
57       when 'int'
58         @generator.int *args
59       when 'let'
60         @generator.let *args
61       when 'return'
62         @generator.ret *args
63       when 'section'
64         @generator.section *args
65       when 'set'
66         @generator.set *args
67       when 'string'
68         @generator.string *args
69       when 'tail-call'
70         @generator.tail_call *args
71       else
72         raise "Unknown action: #{words[0]}"
73       end
74     end
76     @generator.write @output
77   end
78 end