Class: Typisch::Type::String

Inherits:
Constructor show all
Defined in:
lib/typisch/string.rb

Overview

String types support refinement types, specifying a set of allowed values, or a maximum length.

About ruby Symbols: these are a pain in the arse. For now I’m allowing them to type-check interchangably with Strings. Since Typisch isn’t specifically designed for Ruby’s quirks but for more general data interchange, I don’t think Symbol should have a special priviledged type of its own.

Nevertheless if we ever allow custom type tags on String types (as we do for Object types at the moment) we could perhaps allow Symbol as a specially-tagged psuedo string like type. Although it’s not a subclass of String, so hmm.

Constant Summary collapse

Infinity =
1.0/0

Constants inherited from Constructor

Constructor::CONSTRUCTOR_TYPE_SUBCLASSES

Instance Attribute Summary

Attributes inherited from Typisch::Type

#name

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Constructor

#alternative_types, #check_type, inherited, #type_lattice

Methods inherited from Typisch::Type

#<, #<=, #<=>, #==, #===, #>, #>=, #alternative_types, #annotations, #annotations=, #canonicalize!, #excluding_null, #inspect, #recursive?, #subexpression_types, subtype?, #target, #to_string

Constructor Details

#initialize(refinements = {}) ⇒ String

Returns a new instance of String.



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

def initialize(refinements={})
  @refinements = refinements
  if @refinements[:values] && !@refinements[:values].is_a?(::Set)
    @refinements[:values] = ::Set.new(refinements[:values])
  end
end

Class Method Details

.check_subtype(x, y) ⇒ Object



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

def check_subtype(x, y)
  x.equal?(y) || (
    (x.max_length || Infinity) <= (y.max_length || Infinity) &&
    (!y.values || (x.values && x.values.subset?(y.values)))
  )
end

.tagObject



16
17
18
# File 'lib/typisch/string.rb', line 16

def tag
  "String"
end

.top_typeObject



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

def top_type(*)
  @top_type ||= new
end

Instance Method Details

#max_lengthObject



41
42
43
# File 'lib/typisch/string.rb', line 41

def max_length
  @refinements[:max_length]
end

#shallow_check_type(instance) ⇒ Object



61
62
63
64
65
# File 'lib/typisch/string.rb', line 61

def shallow_check_type(instance)
  (::String === instance || ::Symbol === instance) &&
  (!values     || values.include?(instance.to_s)) &&
  (!max_length || instance.to_s.length <= max_length)
end

#tagObject



49
50
51
# File 'lib/typisch/string.rb', line 49

def tag
  self.class.tag
end

#to_sObject



53
54
55
# File 'lib/typisch/string.rb', line 53

def to_s(*)
  @name ? @name.inspect : "string(#{@refinements.inspect})"
end

#valuesObject



45
46
47
# File 'lib/typisch/string.rb', line 45

def values
  @refinements[:values]
end