hammer-parser

Ruby bindings for hammer, a parsing library.

Notes

Development

  1. cd src/bindings/ruby.

  2. Run bundle install to install dependencies.

  3. Run bundle console to open irb with hammer loaded.

  4. To run tests, just run bundle exec rake test.

Installation

  1. Download the hammer source code, and make it available system wide with the bindings.

git clone https://github.com/UpstandingHackers/hammer

cd hammer

scons bindings=ruby

sudo scons bindings=ruby install

  1. On linux, you will have to do

sudo ldconfig

  1. Build the gem gem build hammer-parser.gemspec

  2. Install the gem gem install hammer-parser-x.x.x.gem

Examples

Add hammer to your Gemfile.

gem 'hammer-parser'

Use hammer in your project.

require 'hammer-parser'

Building a parser

parser = Hammer::Parser.build {
  token 'Hello '
  choice {
    token 'Mom'
    token 'Dad'
  }
  token '!'
}

Also possible:

parser = Hammer::ParserBuilder.new
  .token('Hello ')
  .choice(Hammer::Parser.token('Mom'), Hammer::Parser.token('Dad'))
  .token('!')
  .build

More like hammer in C:

h = Hammer::Parser
parser = h.sequence(h.token('Hello '), h.choice(h.token('Mom'), h.token('Dad')), h.token('!'))

Parsing

result = parser.parse 'Hello Mom!'
=> #<HParseResult>
result = parser.parse 'Hello Someone!'
=> nil

The parse method returns an HParseResult object, which needs to be kept around until you're entirely done with the parse tree, which can be accessed with result.ast.

While the AST can be accessed using the same interface as the C HParsedToken type, we recommend using result.ast.unmarshal instead. This converts the entire parse tree into a standalone Ruby-native datastructure which will likely be much easier to work with.