Class: Yagg::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/yagg/parsery.rb

Constant Summary collapse

ParseError =
Class.new(Exception)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ Parser

Returns a new instance of Parser.



6
7
8
# File 'lib/yagg/parsery.rb', line 6

def initialize(text)
  @source = text
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



4
5
6
# File 'lib/yagg/parsery.rb', line 4

def body
  @body
end

#headerObject

Returns the value of attribute header.



4
5
6
# File 'lib/yagg/parsery.rb', line 4

def header
  @header
end

#rulesObject

Returns the value of attribute rules.



4
5
6
# File 'lib/yagg/parsery.rb', line 4

def rules
  @rules
end

#token_groupsObject

Returns the value of attribute token_groups.



4
5
6
# File 'lib/yagg/parsery.rb', line 4

def token_groups
  @token_groups
end

#tokensObject

Returns the value of attribute tokens.



4
5
6
# File 'lib/yagg/parsery.rb', line 4

def tokens
  @tokens
end

Instance Method Details

#parseObject



55
56
57
58
59
# File 'lib/yagg/parsery.rb', line 55

def parse
  setup_sections
  parse_tokens
  parse_rules
end

#parse_rule(arr) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/yagg/parsery.rb', line 26

def parse_rule(arr)
   arr = arr[0..-1]
   name = arr.shift
   arr.shift
   groups = [[]]
   arr.each do |t|
     if t == '|'
       groups.push []
     else
       groups.last.push t
     end
   end
   {name => groups}
end

#parse_rulesObject



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/yagg/parsery.rb', line 41

def parse_rules
   tokens = self.body.scan(/[^'\s]+|'.'/).to_a
   self.token_groups = [[]]
   tokens.each do |t|
     if t != ';'
       self.token_groups.last << t
     else
       self.token_groups << []
     end
   end
   self.token_groups.pop if self.token_groups.last.empty?
   self.rules = self.token_groups.inject({}){|a, b| a.update(parse_rule(b))}
end

#parse_tokensObject



22
23
24
# File 'lib/yagg/parsery.rb', line 22

def parse_tokens
  self.tokens = self.header.scan(/^%token(.*)/).flat_map{|x| x.flat_map{|y| y.split(" ")}}
end

#resultObject



10
11
12
# File 'lib/yagg/parsery.rb', line 10

def result
  self
end

#setup_sectionsObject



14
15
16
17
18
19
20
# File 'lib/yagg/parsery.rb', line 14

def setup_sections
  if @source =~ /([\w\W]*?)^%%\s*([\w\W]*?)^%%\s*/
    self.header, self.body, * = $1, $2
  else
    raise ParseError, "can't recognize format"
  end
end