module Rattler::Compiler::Optimizer

The Optimizer transforms parser models into equivalent models that can result in more efficient parsing code. This is primarily achieved by converting regular expressions into equivalent Regexp patterns, thus reducing object instantiation and method dispatch and having StringScanner do as much of the parsing work as possible.

Constants

FlattenSequence

Nested sequence expressions can be flattened without affecting how they parse given certain conditions

JoinMatchSequence

Sequences of Regexp matches can be joined into a single Regexp match using capturing groups if necessary.

JoinPredicateMatch

A predicate and an adjacent Regexp match in a Sequence can be joined into a single Regexp match.

JoinPredicateOrMatch

A predicate and an adjacent Regexp match in a Choice can be joined into a single Regexp match.

Public Class Methods

optimize(model, opts={}) click to toggle source

@param [Rattler::Parsers::Grammar, Rattler::Parsers::RuleSet, Rattler::Parsers::Rule, Rattler::Parsers::Parser]

model the model to be optimized

@param [Hash] opts options for the optimizer @return an optimized parser model

# File lib/rattler/compiler/optimizer.rb, line 20
def optimize(model, opts={})
  case model
  when Grammar then optimize_grammar model, opts
  when RuleSet then optimize_rule_set model, opts
  else optimizations.apply model, default_context(opts)
  end
end

Private Class Methods

default_context(opts) click to toggle source
# File lib/rattler/compiler/optimizer.rb, line 30
def default_context(opts)
  OptimizationContext[opts.merge :type => :capturing]
end
optimize_grammar(grammar, opts) click to toggle source
# File lib/rattler/compiler/optimizer.rb, line 34
def optimize_grammar(grammar, opts)
  grammar.with_rules optimize_rule_set(grammar.rules, opts)
end
optimize_rule_set(rule_set, opts) click to toggle source
# File lib/rattler/compiler/optimizer.rb, line 38
def optimize_rule_set(rule_set, opts)
  context = default_context(opts).with(:rules => rule_set)
  rule_set = rule_set.map_rules {|_| optimizations.apply _, context }
  context = context.with(:rules => rule_set)
  rule_set.select_rules {|_| context.relavent? _ }
end