Sha256: 9d3f57d65a98df0f18ecb4af382d2e6aaa825559e6fc9142aaf5985a1f0a5bc9

Contents?: true

Size: 1.66 KB

Versions: 2

Compression:

Stored size: 1.66 KB

Contents

module Gisele
  module Language
    class IfToCase < Rewriter
      alias :on_missing :copy_and_applyall

      def on_if_st(node)
        condition, dost, *clauses = node.children

        # create case_st with same markers as the if_st
        when_clause = [:when_clause, condition, mainflow.call(dost)]
        when_clause = node(when_clause, node.markers.dup)
        base        = [:case_st, nil, when_clause]
        base        = node(base, node.markers.dup)

        # this is the condition for elsif clauses
        @condition = negate(condition.last)

        # make injection now
        clauses.inject base do |memo,clause|
          memo << call(clause)
        end
      end

      def on_elsif_clause(node)
        condition, dost, = node.children

        # install new conditions for me and next elsif clauses
        condition = condition.last
        previous  = @condition
        @condition = [:bool_and, negate(condition), @condition]

        # convert elsif to when and keep the markers
        base = \
          [:when_clause,
            [:bool_expr, [:bool_and, condition, previous]],
            mainflow.call(dost) ]
        node(base, node.markers.dup)
      end

      def on_else_clause(node)
        dost, = node.children

        # convert else to when and keep the markers
        base = \
          [:when_clause,
            [:bool_expr, @condition],
            mainflow.call(dost)]
        node(base, node.markers.dup)
      end

      private

      def negate(cond)
        if cond.rule_name == :bool_not
          cond.last
        else
          [:bool_not, cond]
        end
      end

    end # class IfToCase
  end # module Language
end # module Gisele

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
gisele-0.4.0 lib/gisele/language/processors/if_to_case.rb
gisele-0.3.0 lib/gisele/language/if_to_case.rb