Class: Typisch::Type::Union

Inherits:
Typisch::Type show all
Defined in:
lib/typisch/union.rb

Direct Known Subclasses

Any, Nothing

Instance Attribute Summary collapse

Attributes inherited from Typisch::Type

#name

Instance Method Summary collapse

Methods inherited from Typisch::Type

#<, #<=, #<=>, #==, #===, #>, #>=, #annotations, #annotations=, #inspect, #recursive?, subtype?, #target, #to_s

Constructor Details

#initialize(*alternative_types) ⇒ Union

Returns a new instance of Union.



6
7
8
# File 'lib/typisch/union.rb', line 6

def initialize(*alternative_types)
  @alternative_types = alternative_types
end

Instance Attribute Details

#alternative_typesObject (readonly) Also known as: subexpression_types

Returns the value of attribute alternative_types.



3
4
5
# File 'lib/typisch/union.rb', line 3

def alternative_types
  @alternative_types
end

Instance Method Details

#canonicalize!Object



24
25
26
27
28
29
30
31
# File 'lib/typisch/union.rb', line 24

def canonicalize!
  @alternative_types.map!(&:target)

  unless @alternative_types.all? {|t| Type::Constructor === t} &&
         (tags = @alternative_types.map(&:tag)).uniq.length == tags.length
    raise TypeDeclarationError, "the types in a Union must be constructor types with different tags"
  end
end

#check_type(instance, &recursively_check_type) ⇒ Object



10
11
12
13
# File 'lib/typisch/union.rb', line 10

def check_type(instance, &recursively_check_type)
  type = @alternative_types.find {|t| t.shallow_check_type(instance)}
  type && recursively_check_type[type, instance]
end

#excluding_nullObject



19
20
21
22
# File 'lib/typisch/union.rb', line 19

def excluding_null
  types = @alternative_types.reject {|t| Type::Null === t}
  types.length == 1 ? types.first : Type::Union.new(*types)
end

#shallow_check_type(instance) ⇒ Object



15
16
17
# File 'lib/typisch/union.rb', line 15

def shallow_check_type(instance)
  @alternative_types.any? {|t| t.shallow_check_type(instance)}
end

#to_string(depth, indent) ⇒ Object



33
34
35
36
37
# File 'lib/typisch/union.rb', line 33

def to_string(depth, indent)
  next_indent = "#{indent}  "
  types = @alternative_types.map {|t| t.to_s(depth+1, next_indent)}
  "union(\n#{next_indent}#{types.join(",\n#{next_indent}")}\n#{indent})"
end