Class: RBS::Substitution

Inherits:
Object
  • Object
show all
Defined in:
lib/rbs/substitution.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSubstitution

Returns a new instance of Substitution.



12
13
14
# File 'lib/rbs/substitution.rb', line 12

def initialize()
  @mapping = {}
end

Instance Attribute Details

#instance_typeObject

Returns the value of attribute instance_type.



6
7
8
# File 'lib/rbs/substitution.rb', line 6

def instance_type
  @instance_type
end

#mappingObject (readonly)

Returns the value of attribute mapping.



5
6
7
# File 'lib/rbs/substitution.rb', line 5

def mapping
  @mapping
end

Class Method Details

.build(variables, types, instance_type: nil, &block) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rbs/substitution.rb', line 20

def self.build(variables, types, instance_type: 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

Instance Method Details

#+(other) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/rbs/substitution.rb', line 66

def +(other)
  return self if other.empty?
  return other if self.empty?

  Substitution.new.tap do |subst|
    subst.mapping.merge!(mapping)

    other.mapping.each do |var, type|
      if mapping.key?(var)
        subst.add(from: var, to: self[type])
      else
        subst.add(from: var, to: type)
      end
    end
  end
end

#add(from:, to:) ⇒ Object



16
17
18
# File 'lib/rbs/substitution.rb', line 16

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

#apply(ty) ⇒ Object Also known as: []



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rbs/substitution.rb', line 37

def apply(ty)
  case ty
  when Types::Variable
    # @type var ty: Types::Variable
    mapping[ty.name] || ty
  when Types::Bases::Instance
    if t = instance_type
      t
    else
      ty
    end
  else
    ty
  end
end

#empty?Boolean

Returns:

  • (Boolean)


8
9
10
# File 'lib/rbs/substitution.rb', line 8

def empty?
  mapping.empty? && instance_type.nil?
end

#without(*vars) ⇒ Object



55
56
57
58
59
60
61
62
63
64
# File 'lib/rbs/substitution.rb', line 55

def without(*vars)
  Substitution.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