Module: Take::Unit::PredictMatch

Included in:
Compiler
Defined in:
lib/take/unit/predict_match.rb

Instance Method Summary collapse

Instance Method Details

#match(name) ⇒ Array

Matches the next token of the input. If it is not of the expected type, it raises a SyntaxError. Otherwise, it returns the token.

Parameters:

  • name (Symbol)

    the token to match.

Returns:

  • (Array)

    the token.

Raises:

  • SyntaxError if the peeked token is invalid.



32
33
34
35
36
37
38
# File 'lib/take/unit/predict_match.rb', line 32

def match(name)
  if name == peek
    input.next
  else
    raise SyntaxError, "Unexpected token #{peek}"
  end
end

#peekSymbol

Returns the type of the next token.

Returns:

  • (Symbol)

    the type of the next token.



43
44
45
46
47
# File 'lib/take/unit/predict_match.rb', line 43

def peek
  input.peek[0]
rescue StopIteration
  nil
end

#predict(*params, actions) ⇒ Object

Makes a prediction based on a set of actions. If the peek token doesn’t have an action, it will try the special action ‘:_`, and then give up. If it finds a corresponding action either time, it will run the action.

Parameters:

  • actions (Hash<Symbol => Symbol>)

Returns:

  • (Object)

    the result of the compiliation.



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/take/unit/predict_match.rb', line 12

def predict(*params, actions)

  action = actions.fetch(peek) do
    actions.fetch(:_)
  end

  if action.respond_to?(:call)
    action.call(*params)
  else
    send(:"compile_#{action}", *params)
  end
end