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.



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

def initialize()
  @mapping = {}
end

Instance Attribute Details

#instance_typeObject

Returns the value of attribute instance_type.



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

def instance_type
  @instance_type
end

#mappingObject (readonly)

Returns the value of attribute mapping.



3
4
5
# File 'lib/rbs/substitution.rb', line 3

def mapping
  @mapping
end

Class Method Details

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



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/rbs/substitution.rb', line 14

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

#add(from:, to:) ⇒ Object



10
11
12
# File 'lib/rbs/substitution.rb', line 10

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

#apply(ty) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rbs/substitution.rb', line 31

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

#without(*vars) ⇒ Object



47
48
49
50
51
52
53
54
55
56
# File 'lib/rbs/substitution.rb', line 47

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