Sha256: e1e5f13e7e79921576d5178426373fea29835b03df8911649cdb7384bbffc364

Contents?: true

Size: 1.44 KB

Versions: 4

Compression:

Stored size: 1.44 KB

Contents

require "babel_bridge"

class TuringParser < BabelBridge::Parser
  ignore_whitespace

  def store
    @store||=[]
  end

  rule :statements, many(:statement,";"), match?(";") do
    def evaluate
      ret = nil
      statement.each do |s|
        ret = s.evaluate
      end
      ret
    end
  end

  rule :statement, "if", :statement, "then", :statements, :else_clause?, "end" do
    def evaluate
      if matches[1].evaluate
        matches[3].evaluate
      else 
        else_clause.evaluate if else_clause
      end
    end
  end
  rule :else_clause, "else", :statements

  rule :statement, "while", :statement, "do", :statements, "end" do
    def evaluate
      while statement.evaluate
        statements.evaluate
      end
    end
  end

  binary_operators_rule :statement, :operand, [[:/, :*], [:+, :-], [:<, :<=, :>, :>=, :==]] do
    def evaluate
      res = left.evaluate.send operator, right.evaluate
      case operator
      when :<, :<=, :>, :>=, :==
        res ? 1 : nil
      else
        res
      end    
    end
  end

  rule :operand, "[", :statement, "]", "=", :statement do
    def evaluate
      parser.store[statement[0].evaluate] = statement[1].evaluate
    end
  end

  rule :operand, "[", :statement, "]" do
    def evaluate
      parser.store[statement.evaluate]
    end
  end

  rule :operand, "(", :statement, ")"
  rule :operand, /[-]?[0-9]+/ do
    def evaluate
      to_s.to_i
    end
  end
end

BabelBridge::Shell.new(TuringParser.new).start

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
babel_bridge-0.5.1 examples/turing/turing_demo.rb
babel_bridge-0.5.0 examples/turing/turing_demo.rb
babel_bridge-0.4.1 examples/turing/turing_demo.rb
babel_bridge-0.4.0 examples/turing/turing_demo.rb