Sha256: ed30b9f1801fcb81a32fd71c843b16bf3dd4ffe3d0034dae95438d487a10269f

Contents?: true

Size: 1.46 KB

Versions: 17

Compression:

Stored size: 1.46 KB

Contents

# frozen_string_literal: true

require_relative '../lang/zenlish_grammar'

module Zenlish
  class ZParser
    # @!attribute [r] engine
    #   @return [Rley::Engine] Facade object of Rley library
    attr_reader(:engine)

    def initialize
      # Create a Rley facade object
      @engine = Rley::Engine.new do |config|
        config.diagnose = true
      end

      # Step 1. Load Zenlish grammar
      @engine.use_grammar(ZenlishGrammar)
    end

    # Parse the sequence of words into a parse tree.
    # @raise [StandardError] Fails when the parse is ambiguous.
    # @return [Rley::PTree;;ParseTree] the resulting parse tree.
    def parse(tokenSeq)
      result = earley_parse(tokenSeq)

      # Convert into a parse tree
      engine.to_ptree(result)
    end

    alias to_ptree parse

    # Parse the sequence of words into a parse forest.
    # Parse forests are needed when dealing with ambiguous input.
    # @return [Rley::SPPF::ParseForest] the resulting parse forest.
    def to_pforest(tokenSeq)
      result = earley_parse(tokenSeq)
      # puts result

      # Convert into a parse forest
      engine.to_pforest(result)
    end

    private

    def earley_parse(tokenSeq)
      result = engine.parse(tokenSeq)

      unless result.success?
        # Stop if the parse failed...
        line1 = "Parsing failed\n"
        line2 = "Reason: #{result.failure_reason.message}"
        raise StandardError, line1 + line2
      end

      result
    end
  end # class
end # module

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
zenlish-0.2.06 lib/zenlish/parser/zparser.rb
zenlish-0.2.05 lib/zenlish/parser/zparser.rb
zenlish-0.2.04 lib/zenlish/parser/zparser.rb
zenlish-0.2.03 lib/zenlish/parser/zparser.rb
zenlish-0.2.02 lib/zenlish/parser/zparser.rb
zenlish-0.2.01 lib/zenlish/parser/zparser.rb
zenlish-0.2.00 lib/zenlish/parser/zparser.rb
zenlish-0.1.25 lib/zenlish/parser/zparser.rb
zenlish-0.1.24 lib/zenlish/parser/zparser.rb
zenlish-0.1.23 lib/zenlish/parser/zparser.rb
zenlish-0.1.22 lib/zenlish/parser/zparser.rb
zenlish-0.1.21 lib/zenlish/parser/zparser.rb
zenlish-0.1.20 lib/zenlish/parser/zparser.rb
zenlish-0.1.19 lib/zenlish/parser/zparser.rb
zenlish-0.1.18 lib/zenlish/parser/zparser.rb
zenlish-0.1.17 lib/zenlish/parser/zparser.rb
zenlish-0.1.16 lib/zenlish/parser/zparser.rb