Skip to content

mikebaldry/lexr

Repository files navigation

Lexr

Lexr is a lightweight lexical analyser DSL written in ruby, it has no dependencies, has good test coverage, looks pretty and reads well.

Installation

Install the gem and add to the application's Gemfile by executing:

$ bundle add lexr

If bundler is not being used to manage dependencies, install the gem by executing:

$ gem install lexr

Usage

As an example, here is a simple math expression lexer

require 'rubygems'
require 'lexr'

ExpressionLexer = Lexr.that do
  ignores /\s+/ => :whitespace

  legal_place_for_binary_operator = lambda do |prev|
    %i[
      addition subtraction
      multiplication division
      left_parenthesis start
    ].include?(prev.type)
  end

  matches "+" => :addition, unless: legal_place_for_binary_operator
  matches "-" => :subtraction, unless: legal_place_for_binary_operator
  matches "*" => :multiplication, unless: legal_place_for_binary_operator
  matches "/" => :division, unless: legal_place_for_binary_operator

  matches "(" => :left_parenthesis
  matches ")" => :right_parenthesis

  matches /[-+]?[0-9]*\.?[0-9]+/ => :number, convert_with: ->(v) { Float(v) }
end

lexer = ExpressionLexer.new("-1 * 12.5 / (55 + 2 - -56)")

until lexer.end?
  puts lexer.next
end

results in an output of

number(-1.0)
multiplication(*)
number(12.5)
division(/)
left_parenthesis(()
number(55.0)
addition(+)
number(2.0)
subtraction(-)
number(-56.0)
right_parenthesis())
end()

if you added a % in there somewhere, you'd get a Lexr::UnmatchableTextError with a message like this:

=> Unexpected character '%' at position 5

and that is pretty much every feature so far. Please let me know of any bugs or additions that you'd like to see!

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and the created tag, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/mikebaldry/lexr. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

License

The gem is available as open source under the terms of the MIT License.

Code of Conduct

Everyone interacting in the Lexr project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

About

A simple but powerful lexical analyser for Ruby

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published