Sha256: 68d1f5977b6a1498c06f9344346e564fed2130972698d86153859a6c7bdf23e3

Contents?: true

Size: 1.82 KB

Versions: 2

Compression:

Stored size: 1.82 KB

Contents

# encoding: utf-8

require "set"

module Antelope
  class Grammar
    # Manages precedence for tokens.
    module Precedences
      # Accesses the generated precedence list.  Lazily generates
      # the precedence rules on the go, and then caches it.
      #
      # @return [Array<Ace::Precedence>]
      def precedence
        @_precedence ||= generate_precedence
      end

      # Finds a precedence rule for a given token.  If no direct
      # rule is defined for that token, it will check for a rule
      # defined for the special symbol, `:_`.  By default, there
      # is always a rule defined for `:_`.
      #
      # @param token [Ace::Token, Symbol]
      # @return [Ace::Precedence]
      def precedence_for(token)
        token = token.name if token.is_a?(Token)

        prec = precedence.
          detect { |pr| pr.tokens.include?(token) } ||
        precedence.
          detect { |pr| pr.tokens.include?(:_) }

        prec
      end

      private

      # Generates the precedence rules.  Loops through the compiler
      # given precedence settings, and then adds two default
      # precedence rules; one for `:$` (level 0, nonassoc), and one
      # for `:_` (level 1, nonassoc).
      #
      # @return [Array<Ace::Precedence>]
      def generate_precedence
        size = @compiler.options[:prec].size + 1
        index = 0
        precedence = []

        while index < size - 1
          prec = @compiler.options[:prec][index]
          precedence <<
            Precedence.new(prec[0], prec[1..-1].to_set,
            size - index)
          index += 1
        end

        precedence <<
          Precedence.new(:nonassoc, [:$end].to_set, 0) <<
          Precedence.new(:nonassoc, [:_].to_set, 1)
        precedence.sort_by(&:level).reverse
      end

    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
antelope-0.3.2 lib/antelope/grammar/precedences.rb
antelope-0.3.0 lib/antelope/grammar/precedences.rb