Sha256: 620cde1305cb4cd9e6a3f45081402f269ebcadc46a56fabe0d83524bd92764e6

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

# encoding: utf-8
# frozen_string_literal: true

module Carbon
  module Compiler
    class Parser
      # helpers that manage the state of the parser.  This can be things like
      # peeking, shifting, and erroring.
      module Helpers
        # Peeks to the next token.  If peeking would cause a `StopIteration`
        # error, it instead returns the last value that was peeked.
        #
        # @return [Scanner::Token]
        def peek
          value = @enum.peek
          @_last = value
        rescue StopIteration
          @_last
        end

        # Checks to see if any of the given types includes the next token.
        #
        # @param types [Symbol] The possible types.
        # @return [Boolean]
        def peek?(*types)
          types.include?(peek.type)
        end

        # Shifts to the next token, and returns the old token.
        #
        # @return [Scanner::Token]
        def shift
          @enum.next
        end

        # Sets up an expectation for a given token.  If the next token is
        # an expected token, it shifts, returning the token; otherwise,
        # it {#error}s with the token information.
        #
        # @param tokens [Symbol] The expected tokens.
        # @return [Scanner::Token]
        def expect(*tokens)
          return shift if peek?(*tokens)
          error(tokens)
        end

        # Errors, noting the expected tokens, the given token, the location
        # of given tokens.  It does this by emitting a diagnostic.  The
        # diagnostic is only allowed to be a {Metanostic::Mode::PANIC}
        # diagnostic, so this is garenteed to error.
        #
        # @param tokens [<Symbol>] The expected tokens.
        # @return [void]
        def error(tokens)
          @file.emit("Syntax/Token/Unexpected", peek.location,
            [peek.type.inspect, tokens.map(&:inspect).join(", ")])
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
carbon-compiler-0.2.0 lib/carbon/compiler/parser/helpers.rb