Module: Parspec

Defined in:
lib/parspec.rb,
lib/parspec/cli.rb,
lib/parspec/parser.rb,
lib/parspec/version.rb,
lib/parspec/shared_transform.rb,
lib/parspec/parser_spec_transform.rb,
lib/parspec/transformer_spec_transform.rb

Defined Under Namespace

Classes: Cli, Parser, ParserSpecTransform, SharedTransform, TransformerSpecTransform

Constant Summary collapse

Error =
Class.new StandardError
ParseError =
Class.new Error
TransformError =
Class.new Error
CLI =
Cli.instance
VERSION =
'1.0.0'

Class Method Summary collapse

Class Method Details

.deepest_cause(cause) ⇒ Object

Internal: helper for finding the deepest cause for a parse error



48
49
50
51
52
53
54
# File 'lib/parspec.rb', line 48

def self.deepest_cause(cause)
  if cause.children.any?
    deepest_cause(cause.children.first)
  else
    cause
  end
end

.translate(file_or_str, options = {}) ⇒ Object



16
17
18
19
20
21
22
# File 'lib/parspec.rb', line 16

def self.translate(file_or_str, options = {})
  if File.exist?(file_or_str)
    translate_file(file_or_str, options)
  else
    translate_string(file_or_str, options)
  end
end

.translate_file(filename, options = {}) ⇒ Object



24
25
26
# File 'lib/parspec.rb', line 24

def self.translate_file(filename, options = {})
  translate_string(File.read(filename), options)
end

.translate_string(str, options = {}) ⇒ Object



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

def self.translate_string(str, options = {})
  ParserSpecTransform.no_debug_parse = options[:no_debug_parse]
  tree = Parser.new.parse(str)
  tree = SharedTransform.new.apply(tree)
  translation = Parslet::Transform.new do
    spec = ->(type) {
      { header: {type: type, subject_class: simple(:subject_class) },
        rules: subtree(:rules) } }
    rule(spec['parser'])      { ParserSpecTransform.new.apply(tree) }
    rule(spec['transformer']) { TransformerSpecTransform.new.apply(tree) }
  end.apply(tree)
  raise Error, "unexpected translation: #{translation}" unless translation.is_a? String
  translation
rescue Parslet::ParseFailed => e
  deepest = deepest_cause e.cause
  line, column = deepest.source.line_and_column(deepest.pos)
  raise ParseError, "unexpected input at line #{line} column #{column}"
end