Class: AssertType::TypeStringParser

Inherits:
Object
  • Object
show all
Defined in:
lib/assert_type/type_string_parser.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type_string) ⇒ TypeStringParser

Returns a new instance of TypeStringParser.



14
15
16
# File 'lib/assert_type/type_string_parser.rb', line 14

def initialize type_string
  @type_string = type_string
end

Class Method Details

.parse(type_string) ⇒ Object

Parameters:

  • type_string (String)

    like Array<Fixnum>



10
11
12
# File 'lib/assert_type/type_string_parser.rb', line 10

def self.parse type_string
  new(type_string).parse
end

Instance Method Details

#check_angle_brackets_enclose_typeObject



61
62
63
64
65
66
67
68
# File 'lib/assert_type/type_string_parser.rb', line 61

def check_angle_brackets_enclose_type
  previous_name = nil
  tokens.each do |token|
    return false if previous_name == :open_angle && token.name != :word
    previous_name = token.name
  end
  true
end

#check_angle_brackets_matchedObject



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/assert_type/type_string_parser.rb', line 48

def check_angle_brackets_matched
  open_angle_brackets = 0
  tokens.each do |token|
    if token.name == :open_angle
      open_angle_brackets += 1
    elsif token.name == :close_angle
      open_angle_brackets -= 1
    end
    return false if open_angle_brackets < 0
  end
  open_angle_brackets == 0
end

#parseObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/assert_type/type_string_parser.rb', line 18

def parse
  quick_check_tokens
  root = TypeNode.root
  previous_word = root
  current_words = [root]
  tokens.each do |token|
    case token.name
      when :open_angle
        current_words.push previous_word
      when :close_angle
        current_words.pop
      when :word
        current_words.last.children << (previous_word = TypeNode.new(token.value))
      when :comma
        # ignore commas
    end
  end
  root
end

#quick_check_tokensObject



42
43
44
45
46
# File 'lib/assert_type/type_string_parser.rb', line 42

def quick_check_tokens
  unless check_angle_brackets_matched && check_angle_brackets_enclose_type
    raise ParseError.new
  end
end

#tokensObject



38
39
40
# File 'lib/assert_type/type_string_parser.rb', line 38

def tokens
  @tokens ||= TypeStringTokeniser.tokenise @type_string
end