Sha256: d2f1198182ba54d51ff114564177c03150217885024e1482d1083de862f5dd0d

Contents?: true

Size: 1.65 KB

Versions: 4

Compression:

Stored size: 1.65 KB

Contents

require_relative './case/case_conditional'
require_relative './case/case_when'
require_relative './case/case_then'
require_relative './case/case_switch_variable'
require_relative './case/case_else'

module Dentaku
  module AST
    class Case < Node
      def initialize(*nodes)
        @switch = nodes.shift

        unless @switch.is_a?(AST::CaseSwitchVariable)
          raise 'Case missing switch variable'
        end

        @conditions = nodes

        @else = @conditions.pop if @conditions.last.is_a?(AST::CaseElse)

        @conditions.each do |condition|
          unless condition.is_a?(AST::CaseConditional)
            raise "#{condition} is not a CaseConditional"
          end
        end
      end

      def value(context = {})
        switch_value = @switch.value(context)
        @conditions.each do |condition|
          if condition.when.value(context) == switch_value
            return condition.then.value(context)
          end
        end

        if @else
          return @else.value(context)
        else
          raise "No block matched the switch value '#{switch_value}'"
        end
      end

      def dependencies(context = {})
        # TODO: should short-circuit
        switch_dependencies(context) +
        condition_dependencies(context) +
        else_dependencies(context)
      end

      private

      def switch_dependencies(context = {})
        @switch.dependencies(context)
      end

      def condition_dependencies(context = {})
        @conditions.flat_map { |condition| condition.dependencies(context) }
      end

      def else_dependencies(context = {})
        @else ? @else.dependencies(context) : []
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
dentaku-3.3.0 lib/dentaku/ast/case.rb
dentaku-3.2.1 lib/dentaku/ast/case.rb
dentaku-3.2.0 lib/dentaku/ast/case.rb
dentaku-3.1.0 lib/dentaku/ast/case.rb