Sha256: 3d5487a3941bacb72e0ec8d7044892826a4b4bd461a3057fde1054450d82ec80

Contents?: true

Size: 1.89 KB

Versions: 5

Compression:

Stored size: 1.89 KB

Contents

# frozen_string_literal: true

require 'dry/core/cache'

module Dry
  module Schema
    # PrimitiveInferrer is used internally by `Macros::Filled`
    # for inferring a list of possible primitives that a given
    # type can handle.
    #
    # @api private
    class PrimitiveInferrer
      extend Dry::Core::Cache

      # Compiler reduces type AST into a list of primitives
      #
      # @api private
      class Compiler
        # @api private
        def visit(node)
          meth, rest = node
          public_send(:"visit_#{meth}", rest)
        end

        # @api private
        def visit_nominal(node)
          type, _ = node
          type
        end

        # @api private
        def visit_hash(_)
          Hash
        end

        # @api private
        def visit_array(_)
          Array
        end

        # @api private
        def visit_lax(node)
          visit(node)
        end

        # @api private
        def visit_constructor(node)
          other, * = node
          visit(other)
        end

        # @api private
        def visit_enum(node)
          other, * = node
          visit(other)
        end

        # @api private
        def visit_sum(node)
          left, right = node

          [visit(left), visit(right)].flatten(1)
        end

        # @api private
        def visit_constrained(node)
          other, * = node
          visit(other)
        end

        # @api private
        def visit_any(_)
          Object
        end
      end

      # @return [Compiler]
      # @api private
      attr_reader :compiler

      # @api private
      def initialize
        @compiler = Compiler.new
      end

      # Infer predicate identifier from the provided type
      #
      # @return [Symbol]
      #
      # @api private
      def [](type)
        self.class.fetch_or_store(type.hash) do
          Array(compiler.visit(type.to_ast)).freeze
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
dry-schema-1.3.2 lib/dry/schema/primitive_inferrer.rb
dry-schema-1.3.1 lib/dry/schema/primitive_inferrer.rb
dry-schema-1.3.0 lib/dry/schema/primitive_inferrer.rb
dry-schema-1.2.0 lib/dry/schema/primitive_inferrer.rb
dry-schema-1.1.0 lib/dry/schema/primitive_inferrer.rb