Module: Carbon::Compiler::Parser::Helpers

Included in:
Carbon::Compiler::Parser
Defined in:
lib/carbon/compiler/parser/helpers.rb

Overview

helpers that manage the state of the parser. This can be things like peeking, shifting, and erroring.

Instance Method Summary collapse

Instance Method Details

#error(tokens) ⇒ void

This method returns an undefined value.

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.

Parameters:

  • tokens (<Symbol>)

    The expected tokens.



54
55
56
57
# File 'lib/carbon/compiler/parser/helpers.rb', line 54

def error(tokens)
  @file.emit("Syntax/Token/Unexpected", peek.location,
    [peek.type.inspect, tokens.map(&:inspect).join(", ")])
end

#expect(*tokens) ⇒ Scanner::Token

Sets up an expectation for a given token. If the next token is an expected token, it shifts, returning the token; otherwise, it #errors with the token information.

Parameters:

  • tokens (Symbol)

    The expected tokens.

Returns:



42
43
44
45
# File 'lib/carbon/compiler/parser/helpers.rb', line 42

def expect(*tokens)
  return shift if peek?(*tokens)
  error(tokens)
end

#peekScanner::Token

Peeks to the next token. If peeking would cause a ‘StopIteration` error, it instead returns the last value that was peeked.

Returns:



14
15
16
17
18
19
# File 'lib/carbon/compiler/parser/helpers.rb', line 14

def peek
  value = @enum.peek
  @_last = value
rescue StopIteration
  @_last
end

#peek?(*types) ⇒ Boolean

Checks to see if any of the given types includes the next token.

Parameters:

  • types (Symbol)

    The possible types.

Returns:

  • (Boolean)


25
26
27
# File 'lib/carbon/compiler/parser/helpers.rb', line 25

def peek?(*types)
  types.include?(peek.type)
end

#shiftScanner::Token

Shifts to the next token, and returns the old token.

Returns:



32
33
34
# File 'lib/carbon/compiler/parser/helpers.rb', line 32

def shift
  @enum.next
end