File: hash.y

package info (click to toggle)
racc 1.4.8-4
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 868 kB
  • sloc: ruby: 6,176; yacc: 2,077; ansic: 812; sh: 24; makefile: 12
file content (60 lines) | stat: -rw-r--r-- 1,064 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# $Id$
#
# Converting Hash-like string into Ruby's Hash.

class HashParser
  options no_result_var
rule
  hash    : '{' contents '}'   { val[1] }
          | '{' '}'            { Hash.new }
           
                  # Racc can handle string over 2 bytes.
  contents: IDENT '=>' IDENT              { {val[0] => val[2]} }
          | contents ',' IDENT '=>' IDENT { val[0][val[2]] = val[4]; val[0] }
end

---- inner

  def parse(str)
    @str = str
    yyparse self, :scan
  end

  private

  def scan
    str = @str
    until str.empty?
      case str
      when /\A\s+/
        str = $'
      when /\A\w+/
        yield :IDENT, $&
        str = $'
      when /\A=>/
        yield '=>', '=>'
        str = $'
      else
        c = str[0,1]
        yield c, c
        str = str[1..-1]
      end
    end
    yield false, '$'   # is optional from Racc 1.3.7
  end

---- footer

if $0 == __FILE__
  src = <<EOS
{
  name => MyName,
  id => MyIdent
}
EOS
  puts 'Parsing (String):'
  print src
  puts
  puts 'Result (Ruby Object):'
  p HashParser.new.parse(src)
end