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
-
#error(tokens) ⇒ void
Errors, noting the expected tokens, the given token, the location of given tokens.
-
#expect(*tokens) ⇒ Scanner::Token
Sets up an expectation for a given token.
-
#peek ⇒ Scanner::Token
Peeks to the next token.
-
#peek?(*types) ⇒ Boolean
Checks to see if any of the given types includes the next token.
-
#shift ⇒ Scanner::Token
Shifts to the next token, and returns the old token.
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.
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.
42 43 44 45 |
# File 'lib/carbon/compiler/parser/helpers.rb', line 42 def expect(*tokens) return shift if peek?(*tokens) error(tokens) end |
#peek ⇒ Scanner::Token
Peeks to the next token. If peeking would cause a ‘StopIteration` error, it instead returns the last value that was peeked.
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.
25 26 27 |
# File 'lib/carbon/compiler/parser/helpers.rb', line 25 def peek?(*types) types.include?(peek.type) end |
#shift ⇒ Scanner::Token
Shifts to the next token, and returns the old token.
32 33 34 |
# File 'lib/carbon/compiler/parser/helpers.rb', line 32 def shift @enum.next end |