Sha256: 261d612281d03bfb3dff8c553b8e063137a25ae7efbf1bb66f16bf20639826cd

Contents?: true

Size: 945 Bytes

Versions: 19

Compression:

Stored size: 945 Bytes

Contents

# A small example that demonstrates the power of tree pattern matching. Also
# uses '.as(:name)' to construct a tree that can reliably be matched
# afterwards. 

$:.unshift File.dirname(__FILE__) + "/../lib"

require 'pp'
require 'parslet'

module LISP # as in 'lots of insipid and stupid parenthesis'
  class Parser < Parslet::Parser
    rule(:balanced) {
      str('(').as(:l) >> balanced.maybe.as(:m) >> str(')').as(:r)
    }
  
    root(:balanced)
  end

  class Transform < Parslet::Transform
    rule(:l => '(', :m => simple(:x), :r => ')') { 
      # innermost :m will contain nil
      x.nil? ? 1 : x+1
    }
  end
end

parser = LISP::Parser.new
transform = LISP::Transform.new
%w!
  ()
  (())
  ((((()))))
  ((())
!.each do |pexp|
  begin
    result = parser.parse(pexp)
    puts "#{"%20s"%pexp}: #{result.inspect} (#{transform.apply(result)} parens)"
  rescue Parslet::ParseFailed => m
    puts "#{"%20s"%pexp}: #{m}"
  end
  puts
end

Version data entries

19 entries across 19 versions & 3 rubygems

Version Path
parslet-2.0.0 example/parens.rb
parslet-1.8.2 example/parens.rb
parslet-1.8.1 example/parens.rb
parslet-1.8.0 example/parens.rb
swift-pyrite-0.1.1 vendor/bundle/ruby/2.0.0/gems/parslet-1.7.1/example/parens.rb
swift-pyrite-0.1.0 vendor/bundle/ruby/2.0.0/gems/parslet-1.7.1/example/parens.rb
parslet-1.7.1 example/parens.rb
parslet-1.7.0 example/parens.rb
parslet-1.6.2 example/parens.rb
parslet-1.6.1 example/parens.rb
parslet-1.6.0 example/parens.rb
parslet-1.5.0 example/parens.rb
ghazel-parslet-1.4.0.2 example/parens.rb
ghazel-parslet-1.4.0.1 example/parens.rb
parslet-1.4.0 example/parens.rb
parslet-1.3.0 example/parens.rb
parslet-1.2.3 example/parens.rb
parslet-1.2.1 example/parens.rb
parslet-1.2.0 example/parens.rb