Skip to content
jshacks.dev
Functions

How to Use Generators to Build a Tokenizer

Build a tokenizer in JavaScript with a generator that yields numbers, identifiers, operators and strings one at a time, with positions and tests. Node.js 24.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, npm and Vite logos.

A tokenizer turns text into a list of meaningful pieces: the string price * 2 + 1 becomes the identifier price, the operator *, the number 2, and so on. It is the first step of every parser, calculator, template engine and linter. The usual implementation reads the whole input and returns an array. A generator does the same job with less code and a useful property: it produces one token at a time, only when the caller asks. That means a parser can stop early, a huge input is never held as a giant token array and the code reads like the grammar it implements. This post builds a tokenizer with a generator on Node.js 24: numbers, identifiers, operators, strings, whitespace, positions for error messages and a lookahead wrapper for parsers. For the generator mechanics themselves, see building an infinite sequence generator.

What a generator gives you

A generator function is declared with function* and produces values with yield. Calling it does not run the body. It returns an iterator, and each next() call runs the body until the next yield.

JavaScript
function* count() {
  console.log("start");
  yield 1;
  console.log("middle");
  yield 2;
  console.log("end");
}

const it = count();

console.log("created");
console.log(it.next());
console.log(it.next());
console.log(it.next());
Text
created
start
{ value: 1, done: false }
middle
{ value: 2, done: false }
end
{ value: undefined, done: true }

Nothing printed when count() was called. The first next() ran up to the first yield, and the function paused there with its local state intact. That pause is exactly what a tokenizer needs: a position in the input that is remembered between tokens, with no explicit state object.

The tokenizer, one rule at a time

The input is a string, the state is an index into it and each loop iteration looks at one character, decides which kind of token starts there and yields it. Start with whitespace, numbers and single-character operators.

JavaScript
function* tokenize(source) {
  let i = 0;

  while (i < source.length) {
    const char = source[i];

    if (/\s/.test(char)) {
      i += 1;
      continue;
    }

    if (/[0-9]/.test(char)) {
      let end = i;
      while (end < source.length && /[0-9.]/.test(source[end])) end += 1;

      yield { type: "number", value: Number(source.slice(i, end)), start: i };
      i = end;
      continue;
    }

    if ("+-*/()".includes(char)) {
      yield { type: "op", value: char, start: i };
      i += 1;
      continue;
    }

    throw new SyntaxError(`unexpected "${char}" at position ${i}`);
  }
}

console.log([...tokenize("12 + 3.5 * (4 - 1)")].map((t) => t.value).join(" "));
Text
12 + 3.5 * ( 4 - 1 )

The spread [...tokenize(...)] consumes the iterator and collects every token into an array, so you can still get a list when you want one. The map above prints only the values to keep the output short. A character that matches no rule throws a SyntaxError with the position, and every token carries its start, which is what lets later stages point at the exact spot in the source.

The number rule shows a typical choice: read as many digit and dot characters as possible, then convert once with Number. It accepts the malformed 1.2.3, and Number("1.2.3") is NaN. Decide where such errors are reported. Strictness in the tokenizer, a regular expression such as /\d+(\.\d+)?/y, catches it early, while leniency leaves it to the parser.

Using a sticky regular expression

The character-by-character loops get long. A cleaner style is a list of rules, each a regular expression with the sticky flag y, which matches only at lastIndex, not anywhere after it.

JavaScript
const RULES = [
  ["space", /\s+/y],
  ["number", /\d+(?:\.\d+)?/y],
  ["ident", /[A-Za-z_]\w*/y],
  ["string", /"(?:[^"\\]|\\.)*"/y],
  ["op", /[-+*\/()=,<>!]=?/y],
];

function* tokenize(source) {
  let i = 0;

  while (i < source.length) {
    let matched = false;

    for (const [type, pattern] of RULES) {
      pattern.lastIndex = i;
      const match = pattern.exec(source);

      if (!match) continue;

      matched = true;

      if (type !== "space") {
        yield { type, text: match[0], start: i };
      }

      i += match[0].length;
      break;
    }

    if (!matched) {
      throw new SyntaxError(`unexpected "${source[i]}" at position ${i}`);
    }
  }
}

for (const token of tokenize('total >= 10 * price + "a b"')) {
  console.log(token.type, JSON.stringify(token.text), token.start);
}
Text
ident "total" 0
op ">=" 6
number "10" 9
op "*" 12
ident "price" 14
op "+" 20
string "\"a b\"" 22

The sticky flag is what makes this safe: pattern.exec(source) with lastIndex set to i succeeds only if the match begins exactly at i. Without y, a rule could skip ahead and find a match later in the text, silently dropping the characters in between. The rules are tried in order, so put the more specific ones first. The operator rule [-+*\/()=,<>!]=? matches an optional trailing =, which is why >= comes out as one token and not two.

The string rule "(?:[^"\\]|\\.)*" reads quote, then any number of non-quote, non-backslash characters or backslash-escaped pairs, then a closing quote. An unterminated string does not match the string rule, falls through the other rules and ends in the "unexpected" error, which points at the opening quote. That is a reasonable message, and a friendlier one would say "unterminated string".

Position for error messages

A start index is fine for the computer. People want line and column. Compute them from the index only when an error needs them, so the tokenizer stays fast.

JavaScript
function locate(source, index) {
  const before = source.slice(0, index);
  const line = before.split("\n").length;
  const column = index - (before.lastIndexOf("\n") + 1) + 1;

  return { line, column };
}

console.log(locate("a = 1\nb = $", 10));
Text
{ line: 2, column: 5 }

Index 10 is the $ on the second line. The text before it holds one newline, so the line is 2, and the column is its distance from the last newline, counted from one. Computing this lazily costs a pass over the prefix, which only happens once, on failure.

Lookahead for parsers

A parser often needs to peek at the next token without consuming it. A generator cannot un-yield, so wrap it in a small object that holds one token of lookahead.

JavaScript
function createStream(source) {
  const iterator = tokenize(source);
  let buffered = iterator.next();

  return {
    peek: () => (buffered.done ? null : buffered.value),
    next() {
      const current = buffered;
      buffered = iterator.next();
      return current.done ? null : current.value;
    },
  };
}

const stream = createStream("a + b");

console.log(stream.peek().text);
console.log(stream.next().text, stream.next().text, stream.next().text);
console.log(stream.next());
Text
a
a + b
null

peek returns the buffered token without advancing, and next returns it and fetches the following one. At the end both return null, so a parser can test for the end of input without catching an exception. One token of lookahead is enough for many grammars, and the same shape extends to two by buffering an array.

Lazy means early errors can be late

Because the generator runs only as tokens are requested, an error in the last line of the input is raised only when the consumer reaches it. A parser that stops after the first statement never sees it. That is often what you want, for instance in an editor that tokenizes only the visible lines. It also means a call such as tokenize(bad) does not throw by itself, and a test must consume the iterator to see the error.

JavaScript
const tokens = tokenize("1 + $");

console.log("created without error");

try {
  [...tokens];
} catch (error) {
  console.log(error.message);
}
Text
created without error
unexpected "$" at position 4

If you want errors up front, spread into an array first, and accept the memory for the full list.

Where this goes next

A tokenizer is only the first stage. The next stage, the parser, reads tokens and builds a tree that represents the structure: a + b * c becomes a node for + whose right child is the node for *. The stream wrapper above is the interface that parser needs, peek to decide and next to consume, and a recursive descent parser is a small set of functions that call each other following the grammar. Because the tokenizer is lazy, the parser drives it, and a syntax error in the middle of the input is reported at the position of the token where parsing failed.

Two improvements are worth making before the tokenizer meets real input. Keep the original text slice on every token, which is what the text field does here, so error messages can quote it. And decide how to treat unknown characters: stop with an error, as here, or emit an error token and keep going, which lets an editor underline several mistakes at once instead of only the first.

Also keep performance in perspective. Running several regular expressions at each position is simple and fast enough for configuration files, expressions and small languages. For megabytes of source, a hand-written loop over character codes avoids creating match arrays, and a single combined regular expression with named groups lets the engine pick the rule in one pass.

Testing it

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("splits a simple expression", () => {
  const types = [...tokenize("a >= 10")].map((t) => `${t.type}:${t.text}`);
  assert.deepEqual(types, ["ident:a", "op:>=", "number:10"]);
});

test("skips whitespace and keeps positions", () => {
  const [first, second] = tokenize("  x  y");
  assert.equal(first.start, 2);
  assert.equal(second.start, 5);
});

test("rejects an unknown character with its position", () => {
  assert.throws(() => [...tokenize("a # b")], /position 2/);
});

test("can stop early without reading the rest", () => {
  const iterator = tokenize("a $");
  assert.equal(iterator.next().value.text, "a");
});
Text
ℹ tests 4
ℹ pass 4
ℹ fail 0

The last test passes even though the second token would throw, because the generator never got that far. That is the laziness a plain array-returning tokenizer cannot offer.

Taggedbeginner
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.