Sha256: 82d19089b8b8af247155d8c77ef67487fa9c1be81cd968d96c44b8fcbcfdfe4d

Contents?: true

Size: 1.38 KB

Versions: 19

Compression:

Stored size: 1.38 KB

Contents

# A more complex parser that illustrates how a compiler might be constructed.
# The parser recognizes strings and integer literals and constructs almost a
# useful AST from the file contents. 

require 'pp'

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

include Parslet

class LiteralsParser < Parslet::Parser
  rule :space do
    (match '[ ]').repeat(1)
  end
  
  rule :literals do
    (literal >> eol).repeat
  end
  
  rule :literal do
    (integer | string).as(:literal) >> space.maybe
  end
  
  rule :string do
    str('"') >> 
    (
      (str('\\') >> any) |
      (str('"').absent? >> any)
    ).repeat.as(:string) >> 
    str('"')
  end
  
  rule :integer do
    match('[0-9]').repeat(1).as(:integer)
  end
  
  rule :eol do
    line_end.repeat(1)
  end
  
  rule :line_end do
    crlf >> space.maybe
  end
  
  rule :crlf do
    match('[\r\n]').repeat(1)
  end

  root :literals
end

input_name = File.join(File.dirname(__FILE__), 'simple.lit')
file = File.read(input_name)

parsetree = LiteralsParser.new.parse(file)
  
class Lit < Struct.new(:text)
  def to_s
    text.inspect
  end
end
class StringLit < Lit
end
class IntLit < Lit
  def to_s
    text
  end
end

transform = Parslet::Transform.new do
  rule(:literal => {:integer => simple(:x)}) { IntLit.new(x) }
  rule(:literal => {:string => simple(:s)}) { StringLit.new(s) }
end
  
ast = transform.apply(parsetree)
pp ast

Version data entries

19 entries across 19 versions & 3 rubygems

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