Sha256: 1cd6438ae194f8839c72d947d3b9a69105501d25a7a773768a494787bb1f3d86
Contents?: true
Size: 1.28 KB
Versions: 3
Compression:
Stored size: 1.28 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 '../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
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
parslet-1.1.1 | example/string_parser.rb |
parslet-1.1.0 | example/string_parser.rb |
parslet-1.0.1 | example/string_parser.rb |