Sha256: b3f1bdafac4bba717376d3dacc4908cf5050db1e97fc7eba4d5c1b3f88b06e1f

Contents?: true

Size: 1.11 KB

Versions: 2

Compression:

Stored size: 1.11 KB

Contents

module RBS
  class Substitution
    attr_reader :mapping
    attr_accessor :instance_type

    def initialize()
      @mapping = {}
    end

    def add(from:, to:)
      mapping[from] = to
    end

    def self.build(variables, types, instance_type: Types::Bases::Instance.new(location: nil), &block)
      unless variables.size == types.size
        raise "Broken substitution: variables=#{variables}, types=#{types}"
      end

      mapping = variables.zip(types).to_h

      self.new.tap do |subst|
        mapping.each do |v, t|
          type = block_given? ? yield(t) : t
          subst.add(from: v, to: type)
        end

        subst.instance_type = instance_type
      end
    end

    def apply(ty)
      case ty
      when Types::Variable
        mapping[ty.name] || ty
      when Types::Bases::Instance
        instance_type
      else
        ty
      end
    end

    def without(*vars)
      self.class.new.tap do |subst|
        subst.mapping.merge!(mapping)
        vars.each do |var|
          subst.mapping.delete(var)
        end

        subst.instance_type = self.instance_type
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rbs-0.6.0 lib/rbs/substitution.rb
rbs-0.5.0 lib/rbs/substitution.rb