Parsing the Token Array

Now that your lexer is complete, you can turn an input string into an array of Tokens, each of which is either a .Number or a .Plus. The algorithm to parse this sequence of tokens is more restrictive than the algorithm you used for lexing, because the order in which the tokens appear is very important. The rules are:

  • The first token must be a number.

  • After parsing a number, either the parser must be at the end of input, or the next token must be .Plus.

  • After parsing a .Plus, the next token must be a number.

The setup of your parser will be very similar to the lexer, although a bit simpler. The parser does not need separate peek() and advance() methods. They can be combined into one getNextToken() ...

Get Swift Programming: The Big Nerd Ranch Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.