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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.