hammer-parser
Ruby bindings for hammer, a parsing library.
Notes
- I called the gem
hammer-parser
, since there already is a gem namedhammer
.
Development
-
cd src/bindings/ruby
. -
Run
bundle install
to install dependencies. -
Run
bundle console
to openirb
with hammer loaded. -
To run tests, just run
bundle exec rake test
.
Installation
- 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
- On linux, you will have to do
sudo ldconfig
-
Build the gem
gem build hammer-parser.gemspec
-
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.