Class: Ptolemy::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/ptolemy/parser.rb

Overview

The main class that encapsulates all the parsing functionality. It includes the parser generated by the treetop grammar.

Constant Summary collapse

@@parser =

Treetop would’ve generated a parser for TOML based on the grammar

TOMLParser.new

Class Method Summary collapse

Class Method Details

.parse(data) ⇒ Hash

Verifies that the data is encoded in UTF-8 and that the encoding is valid. Parses the data using the TOMLParser generated by Treetop

Parameters:

  • data (String)

    input to be parsed

Returns:

  • (Hash)

    the input parsed into a ruby hash

Raises:

  • (ParseError)

    if there are encoding issues or parsing issues.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/ptolemy/parser.rb', line 28

def self.parse data
  # Data should be a valid UTF-8 encoded string.
  if data.encoding != Encoding::UTF_8
    raise ParseError, "Input is not UTF-8 encoded"
  end
  unless data.valid_encoding?
    raise ParseError, "Input contains invalid UTF-8 byte sequence"
  end

  tree = @@parser.parse data

  if tree.nil?
    raise ParseError, "Parse error at offset: #{@@parser.index}"
  end

  tree.to_value
end