Class: MilkTea::Types::Variant

Inherits:
Base
  • Object
show all
Defined in:
lib/milk_tea/core/types/types.rb

Overview

A user-defined tagged union (discriminated union). Each arm may carry zero or more named payload fields. Arms with no fields carry only the discriminant.

Direct Known Subclasses

VariantInstance

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#accept, #bitwise?, #boolean?, #field_c_name, #float?, #integer?, #numeric?, #sendable?, #void?

Constructor Details

#initialize(name, module_name: nil) ⇒ Variant

Returns a new instance of Variant.



1041
1042
1043
1044
1045
1046
1047
# File 'lib/milk_tea/core/types/types.rb', line 1041

def initialize(name, module_name: nil)
  @name = name
  @module_name = module_name
  @arms = {}       # arm_name => { field_name => type }
  @arm_names = []
  @hash = [self.class, name, module_name].hash
end

Instance Attribute Details

#hashObject (readonly)

Returns the value of attribute hash.



1074
1075
1076
# File 'lib/milk_tea/core/types/types.rb', line 1074

def hash
  @hash
end

#module_nameObject (readonly)

Returns the value of attribute module_name.



1039
1040
1041
# File 'lib/milk_tea/core/types/types.rb', line 1039

def module_name
  @module_name
end

#nameObject (readonly)

Returns the value of attribute name.



1039
1040
1041
# File 'lib/milk_tea/core/types/types.rb', line 1039

def name
  @name
end

Instance Method Details

#arm(name) ⇒ Object



1055
1056
1057
# File 'lib/milk_tea/core/types/types.rb', line 1055

def arm(name)
  @arms[name]
end

#arm_namesObject



1059
1060
1061
# File 'lib/milk_tea/core/types/types.rb', line 1059

def arm_names
  @arm_names
end

#childrenObject



1080
1081
1082
# File 'lib/milk_tea/core/types/types.rb', line 1080

def children
  arm_names.flat_map { |a| arm(a).values }
end

#define_arms(arms_hash) ⇒ Object



1049
1050
1051
1052
1053
# File 'lib/milk_tea/core/types/types.rb', line 1049

def define_arms(arms_hash)
  @arms = arms_hash.freeze
  @arm_names = arms_hash.keys.freeze
  self
end

#eql?(other) ⇒ Boolean Also known as: ==

Returns:

  • (Boolean)


1068
1069
1070
# File 'lib/milk_tea/core/types/types.rb', line 1068

def eql?(other)
  other.class == self.class && other.name == name && other.module_name == module_name
end

#has_payload?(arm_name) ⇒ Boolean

Returns:

  • (Boolean)


1063
1064
1065
1066
# File 'lib/milk_tea/core/types/types.rb', line 1063

def has_payload?(arm_name)
  fields = @arms[arm_name]
  fields && !fields.empty?
end

#to_sObject



1076
1077
1078
# File 'lib/milk_tea/core/types/types.rb', line 1076

def to_s
  module_name ? "#{module_name}.#{name}" : name
end