Class: Pegex::Compiler

Inherits:
Object
  • Object
show all
Defined in:
lib/pegex/compiler.rb

Overview

TODO: Regenerate #make_tree’s (or just #tree’s?) similar to this:

ruby -rpp -rpegex/compiler -e 'pp Pegex::Compiler.new.compile(File.read "share/jsony.pgx").tree''

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCompiler

Returns a new instance of Compiler.



13
14
15
16
17
# File 'lib/pegex/compiler.rb', line 13

def initialize
  @tree = {}
  @_tree = {}
  @atoms = Pegex::Grammar::Atoms.new.atoms
end

Instance Attribute Details

#treeObject

Returns the value of attribute tree.



11
12
13
# File 'lib/pegex/compiler.rb', line 11

def tree
  @tree
end

Instance Method Details

#combinate(rule = nil) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/pegex/compiler.rb', line 37

def combinate rule=nil
  (rule ||= @tree['+toprule']) or return self

  @tree.keys.grep(/^\+/).each {|k| @_tree[k] = @tree[k]}

  combinate_rule rule
  @tree = @_tree
  return self
end

#combinate_object(object) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/pegex/compiler.rb', line 53

def combinate_object object
  if (sub = object['.sep'])
    combinate_object sub
  end
  if object['.rgx']
    combinate_re object
  elsif (rule = object['.ref'])
    if @tree[rule]
      combinate_rule rule
    end
  elsif object['.any']
    object['.any'].each {|elem| combinate_object elem}
  elsif object['.all']
    object['.all'].each {|elem| combinate_object elem}
  elsif object['.err']
  else
    puts "Can't combinate:"
    XXX object
  end
end

#combinate_re(regex) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/pegex/compiler.rb', line 74

def combinate_re regex
  re = regex['.rgx'].clone
  loop do
    re.gsub! /(~+)/ do |m|
      "<ws#{$1.length}>"
    end
    re.gsub! /<(\w+)>/ do |m|
      if @tree[$1]
        @tree[$1]['.rgx'] or fail "'#{$1}' not defined as a single RE"
      else
        @atoms[$1] or fail "'#{$1}' not defined in the grammar"
      end
    end
    break if re == regex['.rgx']
    regex['.rgx'] = re.clone
  end
end

#combinate_rule(rule) ⇒ Object



47
48
49
50
51
# File 'lib/pegex/compiler.rb', line 47

def combinate_rule rule
  return if @_tree[rule]
  object = @_tree[rule] = @tree[rule]
  combinate_object object
end

#compile(grammar) ⇒ Object



19
20
21
22
23
24
# File 'lib/pegex/compiler.rb', line 19

def compile grammar
  parse grammar
  combinate
  native
  return self
end

#nativeObject



92
93
94
# File 'lib/pegex/compiler.rb', line 92

def native
  # TODO
end

#parse(input) ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'lib/pegex/compiler.rb', line 26

def parse input
  parser = Pegex::Parser.new do |p|
    p.grammar = Pegex::Pegex::Grammar.new
    p.receiver = Pegex::Pegex::AST.new
  end

  @tree = parser.parse input

  return self
end