1. Tokenizers & Lexers

Breaking source text into tokens

A compiler or interpreter never sees raw text for long. The very first thing it does is break the source string into a flat list of tokens — small, labeled chunks like NUMBER 42, PLUS +, or IDENTIFIER foo. This process is called lexing (or tokenizing, or scanning — the terms are interchangeable).

Why tokenize at all?

Consider the expression 12 + 34 * 5. As a raw string it's just thirteen characters. A parser that tried to work character-by-character would spend most of its time figuring out where one number ends and the next operator begins. Tokenizing handles that grunt work up front so the parser can think in terms of meaningful symbols.

What is a token?

A token is a pair: a type (sometimes called a tag or kind) and a lexeme (the actual slice of source text). Some tokens also carry a literal value — for instance, the lexeme "hello" has the string value hello with the quotes stripped.

Token { type: NUMBER,  lexeme: "42",  literal: 42  }
Token { type: PLUS,    lexeme: "+",   literal: null }
Token { type: STRING,  lexeme: '"hi"', literal: "hi" }

Most tokenizers also record the line and column where the token appeared, so later stages can produce useful error messages.

A minimal tokenizer by hand

The core loop is dead simple: maintain a cursor into the source string, look at the current character, decide what kind of token it starts, consume characters until the token is complete, emit the token, and advance.

function tokenize(source) {
  const tokens = [];
  let pos = 0;

  while (pos < source.length) {
    const ch = source[pos];

    // Skip whitespace
    if (ch === ' ' || ch === '\n' || ch === '\t') {
      pos++;
      continue;
    }

    // Single-character tokens
    if ('+-*/()'.includes(ch)) {
      tokens.push({ type: ch, lexeme: ch });
      pos++;
      continue;
    }

    // Numbers
    if (ch >= '0' && ch <= '9') {
      let start = pos;
      while (pos < source.length && source[pos] >= '0' && source[pos] <= '9') pos++;
      const lexeme = source.slice(start, pos);
      tokens.push({ type: 'NUMBER', lexeme, literal: Number(lexeme) });
      continue;
    }

    throw new Error(`Unexpected character: '${ch}' at position ${pos}`);
  }

  tokens.push({ type: 'EOF', lexeme: '' });
  return tokens;
}

Feed it 12 + 34 * 5 and you get:

NUMBER "12"  PLUS "+"  NUMBER "34"  STAR "*"  NUMBER "5"  EOF

That's already enough to feed a parser. Everything from here is refinement.

Handling longer tokens

Single characters are easy — one character, one token. The interesting part is multi-character tokens: numbers, identifiers, strings, and multi-character operators like == or <=.

The strategy is always the same: peek ahead. When you see a <, check whether the next character is =. If so, emit LESS_EQUAL and advance two positions. If not, emit LESS and advance one.

Identifiers and keywords

An identifier starts with a letter (or underscore) and continues with letters, digits, or underscores. After consuming the full identifier, you check it against a set of reserved words:

const KEYWORDS = new Set(['if', 'else', 'while', 'return', 'let', 'fn']);

// Inside the tokenizer loop:
if (isAlpha(ch)) {
  let start = pos;
  while (pos < source.length && isAlphaNumeric(source[pos])) pos++;
  const lexeme = source.slice(start, pos);
  const type = KEYWORDS.has(lexeme) ? lexeme.toUpperCase() : 'IDENTIFIER';
  tokens.push({ type, lexeme });
}

This is called maximal munch — always consume the longest possible token. It's the same reason format is one identifier, not the keyword for followed by mat.

String literals

Strings start with a quote character and continue until the matching closing quote. You need to handle escape sequences (\", \\, \n) during scanning:

if (ch === '"') {
  pos++; // skip opening quote
  let value = '';
  while (pos < source.length && source[pos] !== '"') {
    if (source[pos] === '\\') {
      pos++;
      if (source[pos] === 'n') value += '\n';
      else if (source[pos] === '\\') value += '\\';
      else if (source[pos] === '"') value += '"';
    } else {
      value += source[pos];
    }
    pos++;
  }
  pos++; // skip closing quote
  tokens.push({ type: 'STRING', lexeme: source.slice(start, pos), literal: value });
}

Whitespace and comments

Most languages treat whitespace as a separator, not a token — the tokenizer skips it silently. But some languages (Python, Haskell) use indentation for structure. In those cases the tokenizer emits synthetic INDENT and DEDENT tokens by tracking a stack of indentation levels.

Comments are similar — typically consumed and discarded. A // comment runs to the end of the line. A /* */ comment needs a nesting counter or a flag to track whether you're inside one.

Error handling

A good tokenizer doesn't crash on the first bad character. Instead, it records an error, skips the offending character, and keeps going. This way the user sees all the lexical errors at once, not one at a time.

Tokens are a simplification

Tokenizing deliberately throws away information. Whitespace, comments, and the exact formatting of literals are all gone. The parser never sees them. This is a feature — it means the parser's grammar doesn't need rules for "optional spaces between things."

The output of the tokenizer is a flat, ordered list of tokens. The next step — parsing — is where that flat list gets its structure: a tree.

Try It Yourself — Live Tokenizer

Type any code below and watch the tokenizer break it into a colored token stream in real time. Hover over a token chip to see its type and position.

Token Stream

Syntax-Highlighted Source

Token Statistics