Sha256: 8b71ec5673e54a602a4e737d741ba9fab68a71ae496f5cd9ef462fa64c704fed

Contents?: true

Size: 929 Bytes

Versions: 10

Compression:

Stored size: 929 Bytes

Contents

module Lasp
  module_function

  def parse(program)
    build_ast(tokenize(sanitize(program)))
  end

  def build_ast(tokens)
    return if tokens.empty?
    token = tokens.shift

    if token == "("
      form = []
      while tokens.first != ")"
        form << build_ast(tokens)
      end
      tokens.shift
      form
    else
      atom(token)
    end
  end

  def tokenize(string)
    string
      .gsub("(", " ( ")
      .gsub(")", " ) ")
      .scan(/(?:[^\s"]|"[^"]*")+/)
  end

  def atom(token)
    case token
    when "true"        then true
    when "false"       then false
    when "nil"         then nil
    when /\A\d+\z/     then Integer(token)
    when /\A\d+.\d+\z/ then Float(token)
    when /"(.*)"/      then String($1)
    when /:(\w+)/      then String($1) # Symbol style strings are actually just strings
    else token.to_sym
    end
  end

  def sanitize(string)
    string.gsub(/;.*$/, "")
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
lasp-0.7.0 lib/lasp/parser.rb
lasp-0.6.0 lib/lasp/parser.rb
lasp-0.5.0 lib/lasp/parser.rb
lasp-0.4.0 lib/lasp/parser.rb
lasp-0.3.2 lib/lasp/parser.rb
lasp-0.3.1 lib/lasp/parser.rb
lasp-0.3.0 lib/lasp/parser.rb
lasp-0.2.0 lib/lasp/parser.rb
lasp-0.1.1 lib/lasp/parser.rb
lasp-0.1.0 lib/lasp/parser.rb