Sha256: ab62b913bc1d82a8a3048f5fa73daadea2270a339058fc8281ae913c074561e4

Contents?: true

Size: 1.76 KB

Versions: 3

Compression:

Stored size: 1.76 KB

Contents

require 'treetop'
require 'treetop/runtime'
require 'treetop/ruby_extensions'

module Cucumber
  module Parser
    module TreetopExt
      FILE_LINE_PATTERN = /^([\w\W]*?):([\d:]+)$/

      # Parses a file and returns a Cucumber::Ast
      def parse_file(file)
        _, path, lines = *FILE_LINE_PATTERN.match(file)
        if path
          lines = lines.split(':').map { |line| line.to_i }
        else
          path = file
          lines = []
        end

        feature = File.open(path, Cucumber.file_mode('r')) do |io|
          parse_or_fail(io.read, path)
        end
        feature.lines = lines
        feature
      end
    end

    class SyntaxError < StandardError
      def initialize(parser, file, line_offset)
        tf = parser.terminal_failures
        expected = tf.size == 1 ? tf[0].expected_string.inspect : "one of #{tf.map{|f| f.expected_string.inspect}.uniq*', '}"
        after = parser.input[parser.index...parser.failure_index]
        found = parser.input[parser.failure_index..parser.failure_index]
        
        line = parser.failure_line + line_offset
        message = "#{file}:#{line}:#{parser.failure_column}: " +
          "Parse error, expected #{expected}. After #{after.inspect}. Found: #{found.inspect}"
        super(message)
      end
    end
  end
end

module Treetop
  module Runtime
    class SyntaxNode
      def line
        input.line_of(interval.first)
      end
    end
    
    class CompiledParser
      include Cucumber::Parser::TreetopExt
      
      def parse_or_fail(s, file=nil, line=0)
        parse_tree = parse(s)
        if parse_tree.nil?
          raise Cucumber::Parser::SyntaxError.new(self, file, line)
        else
          ast = parse_tree.build
          ast.file = file
          ast
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
aslakhellesoy-cucumber-0.1.99.2 lib/cucumber/parser/treetop_ext.rb
aslakhellesoy-cucumber-0.1.99.3 lib/cucumber/parser/treetop_ext.rb
aslakhellesoy-cucumber-0.1.99.5 lib/cucumber/parser/treetop_ext.rb