Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

75 lines (59 sloc) 1.313 kb
# 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 '../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('"').absnt? >> 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
parsetree = LiteralsParser.new.parse(
File.read('simple.lit'))
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
Jump to Line
Something went wrong with that request. Please try again.