CcCompilers · Lesson 2 of 7
Lexing — Text to Tokens
The lexer reads raw characters and groups them into tokens: words, numbers, operators. It's the simplest stage — simple enough that you can write a real one in 40 lines, and you're about to.
Real lexers add string literals (with escape sequences), multi-character operators (== vs =, maximal munch: always take the longest match), comments, and position tracking so error messages can say line 12, column 8. The core loop never changes: look at the current character, decide the token type, consume characters until it ends.
✦ Tip
'Unexpected token' errors come from this stage's output: the parser received a legal token in an illegal place. 'Unexpected character' or 'invalid token' means the lexer itself choked — usually a stray symbol or an unterminated string.
'Unexpected token' errors come from this stage's output: the parser received a legal token in an illegal place. 'Unexpected character' or 'invalid token' means the lexer itself choked — usually a stray symbol or an unterminated string.