Class: Twostroke::Compiler::TSASM

Inherits:
Object
  • Object
show all
Defined in:
lib/twostroke/compiler/tsasm.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ast, prefix = nil) ⇒ TSASM

Returns a new instance of TSASM.



4
5
6
7
8
# File 'lib/twostroke/compiler/tsasm.rb', line 4

def initialize(ast, prefix = nil)
  @methods = Hash[self.class.private_instance_methods(false).map { |name| [name, true] }]
  @ast = ast
  @prefix = prefix
end

Instance Attribute Details

#astObject

Returns the value of attribute ast.



2
3
4
# File 'lib/twostroke/compiler/tsasm.rb', line 2

def ast
  @ast
end

#bytecodeObject

Returns the value of attribute bytecode.



2
3
4
# File 'lib/twostroke/compiler/tsasm.rb', line 2

def bytecode
  @bytecode
end

#prefixObject

Returns the value of attribute prefix.



2
3
4
# File 'lib/twostroke/compiler/tsasm.rb', line 2

def prefix
  @prefix
end

Instance Method Details

#compile(node = nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/twostroke/compiler/tsasm.rb', line 10

def compile(node = nil)
  if node
    if node.respond_to? :each
      # hoist named functions to top
      node.select { |n| n.is_a?(Twostroke::AST::Function) && n.name }.each { |n| compile n }
      node.reject { |n| n.is_a?(Twostroke::AST::Function) && n.name }.each { |n| compile n }
    elsif node.is_a? Symbol
      send node
    else
      if @methods[type(node)]
        send type(node), node if node
      else
        error! "#{type node} not implemented"
      end
    end
  else
    @indent = 0
    @bytecode = Hash.new { |h,k| h[k] = [] }
    @current_section = :"#{prefix}main"
    @auto_inc = 0
    @sections = [:"#{prefix}main"]
    @break_stack = []
    @continue_stack = []
          
    ast.each { |node| hoist node }
    ast.each { |node| compile node }
    output :undefined
    output :ret
    
    fix_labels
  end
end