Sha256: 1edce3114a8548279e341fc3a7ec20352c58658c419194d67bcbd975c5d22b7f

Contents?: true

Size: 1.95 KB

Versions: 2

Compression:

Stored size: 1.95 KB

Contents

# encoding: utf-8
# frozen_string_literal: true

require "carbon/concrete/item/trait/expectation"

module Carbon
  module Concrete
    module Item
      # A trait.  This says that a specific type behaves with a certain set
      # of functions.
      #
      # @api private
      # @note
      #   **This class is frozen upon initialization.**  This means that any
      #   attempt to modify it will result in an error.  In most cases, the
      #   attributes on this class will also be frozen, as well.
      class Trait
        include Base

        # (see Item::Base.from)
        def self.from(type)
          { type: type, expectations: [] }
        end

        # The expectations for the trait.
        #
        # @api semipublic
        # @example
        #   trait.expectations
        #     # => [#<Carbon::Concrete::Item::Trait::Expectation +)]
        # @return [Set<Expectation>]
        attr_reader :expectations

        # Initialize the trait with data.
        #
        # @param data [::Hash] The data to initialize the trait with.
        # @option data [Type] :type The name of the trait type.
        # @option data [<(::String, <Type>, Type)>] :expectations
        #   The expectations that the trait requires.
        def initialize(data)
          @type = data.fetch(:type)
          @generics = @type.generics
          @name = @type.to_s

          derive_expectations(data.fetch(:expectations))
          derive_dependencies
          deep_freeze!
        end

        # (see Base#call)
        def call(_build, _generics)
          # do nothing.
        end

      private

        def derive_expectations(expectations)
          expects = expectations.map { |e| Expectation.new(*e) }
          @expectations = Set.new(expects)
        end

        def derive_dependencies
          @expectations.each do |expect|
            @dependencies.merge(expect.parameters)
            @dependencies << expect.return
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
carbon-core-0.2.1 lib/carbon/concrete/item/trait.rb
carbon-core-0.2.0 lib/carbon/concrete/item/trait.rb