Class: MilkTea::Types::Variant

Inherits:
Base
  • Object
show all
Defined in:
lib/milk_tea/core/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.



1030
1031
1032
1033
1034
1035
1036
# File 'lib/milk_tea/core/types.rb', line 1030

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.



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

def hash
  @hash
end

#module_nameObject (readonly)

Returns the value of attribute module_name.



1028
1029
1030
# File 'lib/milk_tea/core/types.rb', line 1028

def module_name
  @module_name
end

#nameObject (readonly)

Returns the value of attribute name.



1028
1029
1030
# File 'lib/milk_tea/core/types.rb', line 1028

def name
  @name
end

Instance Method Details

#arm(name) ⇒ Object



1044
1045
1046
# File 'lib/milk_tea/core/types.rb', line 1044

def arm(name)
  @arms[name]
end

#arm_namesObject



1048
1049
1050
# File 'lib/milk_tea/core/types.rb', line 1048

def arm_names
  @arm_names
end

#childrenObject



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

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

#define_arms(arms_hash) ⇒ Object



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

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)


1057
1058
1059
# File 'lib/milk_tea/core/types.rb', line 1057

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

#has_payload?(arm_name) ⇒ Boolean

Returns:

  • (Boolean)


1052
1053
1054
1055
# File 'lib/milk_tea/core/types.rb', line 1052

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

#to_sObject



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

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