class RBS::Substitution
Substitution from type variables to types.
The substitution construction is in destructive manner.
sub = Substitution.new sub.add(from: :A, to: type1) sub.add(from: :B, to: type2) sub.instance_type = type3
Attributes
Types::t?
The result of applying this substitution to instance type. nil maps to instance type itself.
Hash[Symbol, Types::t]
A hash containing mapping from type variable name to type.
Public Class Methods
(Array[Symbol] variables, Array[Types::t] types, ?instance_type: Types::t?) ?{ (Types::t) → Types::t } → instance
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/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
Utility method to construct a substitution. Raises an error when variables.size != types.size. instance_type defaults to nil.
Yields types in types and the block value is used if block is given.
() → void
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/lib/rbs/substitution.rb, line 12 def initialize() @mapping = {} end
Public Instance Methods
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/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
(s1 + s2)[t] == s2[s1]
(from: Symbol, to: Types::t) → void
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/lib/rbs/substitution.rb, line 16 def add(from:, to:) mapping[from] = to end
Add mapping to this substitution. Overwrites the previous mapping if same from is given.
(Types::t) → Types::t
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/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
Applies the substitution to given type.
() → bool
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/lib/rbs/substitution.rb, line 8 def empty? mapping.empty? && instance_type.nil? end
Returns true if given substitution is identity.
(*Symbol vars) → Substitution
Source
# File vendor/bundle/ruby/4.0.0/gems/rbs-4.0.3/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
Returns a substitution without variables given in vars.