Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 58 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,53 @@
# Parser

[![Gem Version](https://badge.fury.io/rb/parser.png)](http://badge.fury.io/rb/parser)
[![Build Status](https://travis-ci.org/whitequark/parser.png?branch=master)](https://travis-ci.org/whitequark/parser)
[![Code Climate](https://codeclimate.com/github/whitequark/parser.png)](https://codeclimate.com/github/whitequark/parser)
[![Coverage Status](https://coveralls.io/repos/whitequark/parser/badge.png?branch=master)](https://coveralls.io/r/whitequark/parser)

_Parser_ is a production-ready Ruby parser written in pure Ruby. It performs on par or better than Ripper, Melbourne, JRubyParser or ruby_parser.
_Parser_ is a production-ready Ruby parser written in pure Ruby. It
performs on par or better than Ripper, Melbourne, JRubyParser or
ruby_parser.

## Installation

$ gem install parser
~~~
$ gem install parser
~~~

## Usage

Parse a chunk of code:

~~~ ruby
require 'parser/ruby20'
require 'parser/current'

p Parser::Ruby20.parse("2 + 2")
p Parser::CurrentRuby.parse("2 + 2")
# (send
# (int 2) :+
# (int 2))
~~~

Access the AST's source map:

~~~ ruby
p Parser::CurrentRuby.parse("2 + 2").src

# <Parser::Source::Map::Send:0x007fe0ca8a69b8
# @begin=nil,
# @end=nil,
# @expression=#<Source::Range (string) 0...5>,
# @selector=#<Source::Range (string) 2...3>>

p Parser::CurrentRuby.parse("2 + 2").src.selector.to_source

#=> "+"
~~~

Parse a chunk of code and display all diagnostics:

~~~ ruby
parser = Parser::Ruby20.new
parser = Parser::CurrentRuby.new
parser.diagnostics.consumer = lambda do |diag|
puts diag.render
end
Expand All @@ -45,6 +66,38 @@ p parser.parse(buffer)

If you reuse the same parser object for multiple `#parse` runs, you need to `#reset` it.

You can also use the `ruby-parse` utility (it's bundled with the gem) to play with Parser:

~~~
$ ruby-parse -L -e "2+2"

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like this code block. Lines beginning with $ aren't in the "bash" language, and these comments... just remove highlighting and paste the shell session as-is.

Otherwise, it's fine.

(send
(int 2) :+
(int 2))
2+2
~ selector
~~~ expression
(int 2)
2+2
~ expression
(int 2)
2+2

$ ruby-parse -E -e "2+2"

2+2
^ tINTEGER 2 expr_end [0 <= cond] [0 <= cmdarg]
2+2
^ tPLUS "+" expr_beg [0 <= cond] [0 <= cmdarg]
2+2
^ tINTEGER 2 expr_end [0 <= cond] [0 <= cmdarg]
2+2
^ false "$eof" expr_end [0 <= cond] [0 <= cmdarg]
(send
(int 2) :+
(int 2))
~~~

## Features

* Precise source location reporting.
Expand Down