Class: BabelBridge::Parser

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

Overview

Used to parse with .parse

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeParser

Returns a new instance of Parser.



173
174
175
# File 'lib/parser.rb', line 173

def initialize
  reset_parser_tracking
end

Class Attribute Details

.delimiter_patternObject

Returns the value of attribute delimiter_pattern.



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

def delimiter_pattern
  @delimiter_pattern
end

.module_nameObject

Returns the value of attribute module_name.



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

def module_name
  @module_name
end

.root_ruleObject

Returns the value of attribute root_rule.



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

def root_rule
  @root_rule
end

.rulesObject

Returns the value of attribute rules.



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

def rules
  @rules
end

Instance Attribute Details

#expecting_listObject

Returns the value of attribute expecting_list.



168
169
170
# File 'lib/parser.rb', line 168

def expecting_list
  @expecting_list
end

#failed_parseObject

gets set if the entire input was not matched



171
172
173
# File 'lib/parser.rb', line 171

def failed_parse
  @failed_parse
end

#failure_indexObject

********************************************* ********************************************* parser instance implementation this methods are used for each actual parse run they are tied to an instnace of the Parser Sub-class to you can have more than one parser active at a time



167
168
169
# File 'lib/parser.rb', line 167

def failure_index
  @failure_index
end

#parse_cacheObject

Returns the value of attribute parse_cache.



170
171
172
# File 'lib/parser.rb', line 170

def parse_cache
  @parse_cache
end

#srcObject

Returns the value of attribute src.



169
170
171
# File 'lib/parser.rb', line 169

def src
  @src
end

Class Method Details

.[](i) ⇒ Object



89
90
91
# File 'lib/parser.rb', line 89

def [](i)
  rules[i]
end

.binary_operators_rule(name, operand_rule_name, operators, options = {}, &block) ⇒ Object

options

> right_operators: list of all operators that should be evaluated right to left instead of left-to-write

typical example is the "**" exponentiation operator which should be evaluated right-to-left.


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
78
79
80
81
# File 'lib/parser.rb', line 51

def binary_operators_rule(name,operand_rule_name,operators,options={},&block)
  right_operators = options[:right_operators]
  rule name, many(operand_rule_name,Tools::array_to_or_regexp(operators)).delimiter_name(:operators).as(:operands) do
    self.class_eval &block if block
    class <<self
      attr_accessor :operators_from_rule, :right_operators
      def operator_processor
        @operator_processor||=BinaryOperatorProcessor.new(operators_from_rule,self,right_operators)
      end
    end
    self.right_operators = right_operators
    self.operators_from_rule = operators

    def operator
      @operator||=operator_node.to_s.to_sym
    end

    def operator_processor
      self.class.operator_processor
    end

    # Override the on_post_match method to take the results of the "many" match
    # and restructure it into a binary tree of nodes based on the precidence of
    # the "operators".
    # TODO - Should on_post_match be run after the whole tree matches? If not, will this screw up caching?
    def post_match_processing
      super
      operator_processor.generate_tree operands, operators, parent
    end
  end
end

.couldObject



156
# File 'lib/parser.rb', line 156

def could; PatternElementHash.new.could end

.custom_parser(&block) ⇒ Object



157
# File 'lib/parser.rb', line 157

def custom_parser(&block); PatternElementHash.new.parser(lambda &block) end

.delimiter(*pattern) ⇒ Object



104
105
106
# File 'lib/parser.rb', line 104

def delimiter(*pattern)
  @delimiter = pattern
end

.dontObject



154
# File 'lib/parser.rb', line 154

def dont; PatternElementHash.new.dont end

.ignore_whitespaceObject



100
101
102
# File 'lib/parser.rb', line 100

def ignore_whitespace
  delimiter /\s*/
end

.many(m, delimiter = nil) ⇒ Object



146
# File 'lib/parser.rb', line 146

def many(m,delimiter=nil) PatternElementHash.new.match.many(m).delimiter(delimiter) end

.many!(m, delimiter = nil) ⇒ Object



148
# File 'lib/parser.rb', line 148

def many!(m,delimiter=nil) PatternElementHash.new.dont.match.many(m).delimiter(delimiter) end

.many?(m, delimiter = nil) ⇒ Boolean

Returns:

  • (Boolean)


147
# File 'lib/parser.rb', line 147

def many?(m,delimiter=nil) PatternElementHash.new.optionally.match.many(m).delimiter(delimiter) end

.match(*args) ⇒ Object



151
# File 'lib/parser.rb', line 151

def match(*args) PatternElementHash.new.match(*args) end

.match!(*args) ⇒ Object



152
# File 'lib/parser.rb', line 152

def match!(*args) PatternElementHash.new.dont.match(*args) end

.match?(*args) ⇒ Boolean

Returns:

  • (Boolean)


150
# File 'lib/parser.rb', line 150

def match?(*args) PatternElementHash.new.optionally.match(*args) end

.node_class(name, &block) ⇒ Object



83
84
85
86
87
# File 'lib/parser.rb', line 83

def node_class(name,&block)
  klass=self.rules[name].node_class
  return klass unless block
  klass.class_eval &block
end

.optionallyObject



155
# File 'lib/parser.rb', line 155

def optionally; PatternElementHash.new.optionally end

.rule(name, *pattern, &block) ⇒ Object

Add a rule to the parser

rules can be specified as:

rule :name, to_match1, to_match2, etc...

Can define rules INSIDE class:

class MyParser < BabelBridge::Parser
  rule :name, to_match1, to_match2, etc...
end

Or can define rules OUTSIDE class:

class MyParser < BabelBridge::Parser
end
MyParser.rule :name, to_match1, to_match2, etc...

The first rule added is the root-rule for the parser. You can override by:

class MyParser < BabelBridge::Parser
  root_rule = :new_root_rool
end

The block is executed in the context of the rule-varient’s node type, a subclass of: RuleNode This allows you to add whatever functionality you want to a your nodes in the final parse tree. Also note you can override the on_post_match method. This allows you to restructure the parse tree as it is parsed.



41
42
43
44
45
46
# File 'lib/parser.rb', line 41

def rule(name,*pattern,&block)
  rule = self.rules[name] ||= Rule.new(name,self)
  @root_rule ||= name
  options =  pattern[-1].kind_of?(Hash) ? pattern.pop : {}
  rule.add_variant options.merge(:pattern => pattern), &block
end

Instance Method Details

#cache_match(rule_class, match) ⇒ Object



190
191
192
# File 'lib/parser.rb', line 190

def cache_match(rule_class,match)
  (parse_cache[rule_class]||={})[match.offset]=match
end

#cache_no_match(rule_class, offset) ⇒ Object



194
195
196
# File 'lib/parser.rb', line 194

def cache_no_match(rule_class,offset)
  (parse_cache[rule_class]||={})[offset]=:no_match
end

#cached(rule_class, offset) ⇒ Object



186
187
188
# File 'lib/parser.rb', line 186

def cached(rule_class,offset)
  (parse_cache[rule_class]||={})[offset]
end

#delimiter_patternObject



113
114
115
# File 'lib/parser.rb', line 113

def delimiter_pattern
  self.class.delimiter_pattern
end

#expecting_output(options = {}) ⇒ Object

options => false



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/parser.rb', line 291

def expecting_output(options={})
  return "" if expecting_list.length==0
  common_root=nil
  expecting_list.values.each do |e|
    node=e[:node]
    pl=nodes_interesting_parse_path(node)
    pl.pop # ignore the node itself
    if common_root
      common_root.each_index do |i|
        if pl[i]!=common_root[i]
          common_root=common_root[0..i-1]
          break
        end
      end
    else
      common_root=pl
    end
  end
  <<ENDTXT

Parse path at failure:
#{node_list_string(common_root,[],:verbose=>true)}

Expecting#{expecting_list.length>1 ? ' one of' : ''}:
#{Tools.uniform_tabs(Tools.indent(expecting_list.values.collect do |a|
  list=node_list_string(nodes_interesting_parse_path(a[:node]),common_root,options)
  "#{a[:pattern].inspect}\t#{list}"
end.sort.join("\n"),"  "))}
ENDTXT
end

#log_parsing_failure(index, expecting) ⇒ Object



198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/parser.rb', line 198

def log_parsing_failure(index,expecting)
  if matching_negative?
    # ignored
  elsif index>failure_index
    @expecting_list = {expecting[:pattern] => expecting}
    @failure_index = index
  elsif index == failure_index
    @expecting_list[expecting[:pattern]] = expecting
  else
    # ignored
  end
end

#matching_negativeObject



211
212
213
214
# File 'lib/parser.rb', line 211

def matching_negative
  @matching_negative_depth||=0
  @matching_negative_depth+=1
end

#matching_negative?Boolean

Returns:

  • (Boolean)


220
221
222
# File 'lib/parser.rb', line 220

def matching_negative?
  (@matching_negative_depth||0) > 0
end

#node_list_string(node_list, common_root = [], options = {}) ⇒ Object

options => false



269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/parser.rb', line 269

def node_list_string(node_list,common_root=[],options={})
  return unless node_list
  if options[:verbose]
    node_list[common_root.length..-1]
  else
    [node_list[-1]]
  end.select do |p|
    p.class.to_s.index(BabelBridge.to_s)!=0
  end.map do |p|
    "#{p.relative_class_name}"
  end.join(" > ")
end

#nodes_interesting_parse_path(node) ⇒ Object



282
283
284
285
286
287
# File 'lib/parser.rb', line 282

def nodes_interesting_parse_path(node)
  path = node.parent_list
  path << node
  path.pop while path[-1] && !path[-1].kind_of?(RuleNode)
  path
end

#parse(src, options = {}) ⇒ Object

parse a string, return the root node of the parse tree. If nil is returned, parsing failed. Call .parser_failure_info after failure for a human-readable description of the failure. src: the string to parse options:

offset: where to start in the string for parsing
rule: lets you specify the root rule for matching
partial_match: allow partial matching


231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/parser.rb', line 231

def parse(src, options={})
  offset = options[:offset] || 0
  rule = options[:rule] || self.class.root_rule
  reset_parser_tracking
  @start_time = Time.now
  self.src = src
  root_node = RootNode.new(self)
  raise "No root rule defined." unless rule
  ret = rules[rule].parse(root_node)
  if ret
    if ret.next<src.length && !options[:partial_match] # parse only succeeds if the whole input is matched
      if ret.next >= @failure_index
        @parsing_did_not_match_entire_input=true
        @failure_index = ret.next
        @failed_parse = ret
      end
      ret=nil
    else
      reset_parser_tracking
    end
  end
  @end_time=Time.now
  ret
end

#parse_and_puts_errors(src, out = $stdout) ⇒ Object



260
261
262
263
264
265
266
# File 'lib/parser.rb', line 260

def parse_and_puts_errors(src,out=$stdout)
  ret=parse(src)
  unless ret
    out.puts parser_failure_info
  end
  ret
end

#parse_timeObject



256
257
258
# File 'lib/parser.rb', line 256

def parse_time
  @end_time-@start_time
end

#parser_failure_info(options = {}) ⇒ Object

option: :verbose => true



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/parser.rb', line 323

def parser_failure_info(options={})
  return unless src
  verbose = options[:verbose]
  bracketing_lines=5
  line,col = Tools.line_column(src, failure_index)
  ret=<<-ENDTXT
Parsing error at line #{line} column #{col} offset #{failure_index}

Source:
...
#{(failure_index==0 ? "" : src[0..(failure_index-1)]).last_lines(bracketing_lines)}<HERE>#{src[(failure_index)..-1].first_lines(bracketing_lines)}
...
ENDTXT

  if @parsing_did_not_match_entire_input
    ret+="\nParser did not match entire input.\n"
    if verbose
      ret+="\nParsed:\n#{Tools::indent failed_parse.inspect||"(nothing)"}\n"
    end
  end

  ret+expecting_output
end

#reset_parser_trackingObject



177
178
179
180
181
182
183
184
# File 'lib/parser.rb', line 177

def reset_parser_tracking
  @matching_negative_depth = 0
  @parsing_did_not_match_entire_input = false
  @src = nil
  @failure_index = 0
  @expecting_list = {}
  @parse_cache = {}
end

#rulesObject



117
118
119
# File 'lib/parser.rb', line 117

def rules
  self.class.rules
end

#unmatching_negativeObject



216
217
218
# File 'lib/parser.rb', line 216

def unmatching_negative
  @matching_negative_depth-=1
end