forked from zenspider/ruby-ometa
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.rb
77 lines (67 loc) · 1.97 KB
/
parser.rb
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
$:.unshift "lib"
require 'ometa'
# class OMeta
# @@tally = Hash.new 0
# alias :old_apply :_apply
# at_exit {
# at_exit {
# pp @@tally.sort_by { |k,v| -v }.first(20)
# }
# }
# def _apply rule
# @@tally[caller.first] += 1
# old_apply rule
# end
# end
# later on the idea is to add a Ometa::Grammar function or something
# similar to wrap up the process of creating a ruby class object from
# an ometa grammar file.
#
# as an example (this is missing the optimization pass):
class Ometa
def self.Grammar(filename)
grammar = File.read(filename)
grammar = grammar.gsub(/\n\s*\n/,"\n,\n")
lines = grammar.split("\n")
if /^#standard *(.*)$/.match(lines[0])
$std = $1.strip
puts $std
require "standards/#{$std}/bootstrap.rb"
lines.shift
grammar =lines *"\n"
end
puts grammar
parsed = OMetaParser.parsewith(grammar, 'grammar')
puts parsed.inspect
optimized = OMetaOptimizer.matchwith(parsed, 'optimizeGrammar')
$parsed=optimized
ruby = RubyOMetaTranslator.matchwith(optimized, 'trans')
#ruby = File.read('_debug.rb')
begin
open('_debug.rb', 'w') { |f| f << ruby }
eval ruby
rescue SyntaxError
puts '* error compiling grammar'
puts '* ast:'
require 'pp'
puts '* ruby:'
puts ruby
open('_debug.rb', 'w') { |f| f << ruby }
raise
end
end
end
class Parser < Ometa::Grammar('ometa/ometa2ometa.ometa')
def self.parse str
matchwith str, 'trans'
end
end
require 'pp'
grammar=Parser.parse($parsed)
puts grammar
parsed = OMetaParser.parsewith(grammar, 'grammar')
parsed = OMetaOptimizer.matchwith(parsed, 'optimizeGrammar')
pp parsed
pp $parsed
puts parsed ==$parsed
[ ["And", ["App", "anything"], ["App", "anything"]] ,["Grammar", "RubyOMeta2OMeta", "OMeta", ["Rule", "trans", ["t", "ans"],[], ["Or", ["And", ["And", ["Form", ["Or", ["And", ["Set", "t", ["App", "anything"]], ["Set", "ans", ["App", "apply", "t"]]]]]]]]]] ].each{|s| puts Parser.parse(s).inspect}