Sha256: da0b56ad5e2959ad4da3c61c9f22c2f5c7483e38fc56b971aaeae307a56d7415

Contents?: true

Size: 774 Bytes

Versions: 2

Compression:

Stored size: 774 Bytes

Contents

class AbstractSyntaxTreeBuilder

  def initialize(postfix)
    @postfix = postfix
  end

  def build_tree
    until @postfix.length == 1
      operator_index = first_operator_index
      fail NotEnoughOperatorsException if operator_index.nil?
      exp = Operator.factory!(@postfix.slice!(operator_index))
      most_left_child = operator_index - exp::ARITY
      fail NotEnoughOperandsException, expression: exp if most_left_child < 0
      children = @postfix.slice!(most_left_child, exp::ARITY)
      @postfix.insert(most_left_child, exp.new(*children))
    end
    @postfix.first
  end

  private

  def first_operator_index
    @postfix.find_index { |token|
      begin
        Operator.factory!(token)
        true
      rescue
        false
      end
    }
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
lamep-0.2.1 lib/lamep/abstract_syntax_tree_builder.rb
lamep-0.2 lib/lamep/abstract_syntax_tree_builder.rb