Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Write a tokenizer (lexer) in JavaScript

114 A tokeniser that can say where it went wrong

hard

Write a tokeniser for a small configuration language — names, numbers, quoted strings, { } = , and # comments — where every token records the line and column it started at. Then use those positions for errors: an unexpected character must report its own line and column and print a caret under it, and an unterminated string must report where the string opened rather than where the input ran out. Finish with an invariant: each token's recorded position must be enough to cut its exact text back out of the source.

Stuck? Three hints, smallest first
  1. 1. One advance() that moves the index is the only place allowed to touch line and column. A newline sets the column back to 1 and adds a line; everything else adds a column.
  2. 2. Capture the line and column into locals before you consume a token, because by the time you know what it was you are already past its start.
  3. 3. For an unterminated string the useful position is the opening quote, which you still have in those locals. Reporting the end of the file tells the reader nothing.

The answer

const isSpace = (c) => c === ' ' || c === '\t' || c === '\n' || c === '\r';
const isDigit = (c) => c >= '0' && c <= '9';
const startsName = (c) => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c === '_';
const inName = (c) => startsName(c) || isDigit(c);
const sourceLines = (source) => source.split(/\r\n|\r|\n/);

function tokenise(source) {
  const tokens = [];
  let i = 0;
  let line = 1;
  let column = 1;

  // The only place line and column are allowed to change.
  const advance = () => {
    if (source[i] === '\r' && source[i + 1] === '\n') { i += 2; line++; column = 1; return; }
    if (source[i] === '\n' || source[i] === '\r') { i += 1; line++; column = 1; return; }
    i += 1;
    column += 1;
  };

  const fail = (message, atLine, atColumn) => {
    const err = new Error(message + ' at line ' + atLine + ', column ' + atColumn);
    err.name = 'SyntaxError';
    err.line = atLine;
    err.column = atColumn;
    const text = sourceLines(source)[atLine - 1] || '';
    err.caret = text + '\n' + ' '.repeat(atColumn - 1) + '^';
    throw err;
  };

  while (i < source.length) {
    if (isSpace(source[i])) { advance(); continue; }
    if (source[i] === '#') {
      while (i < source.length && source[i] !== '\n' && source[i] !== '\r') advance();
      continue;
    }

    const from = i;
    const atLine = line;
    const atColumn = column;

    if (source[i] === '"') {
      advance();
      while (i < source.length && source[i] !== '"') {
        if (source[i] === '\n' || source[i] === '\r') fail('unterminated string', atLine, atColumn);
        advance();
      }
      if (i >= source.length) fail('unterminated string', atLine, atColumn);
      advance();
      const text = source.slice(from, i);
      tokens.push({ type: 'string', value: text.slice(1, -1), text, line: atLine, column: atColumn });
      continue;
    }

    if (isDigit(source[i])) {
      while (i < source.length && (isDigit(source[i]) || source[i] === '.')) advance();
      const text = source.slice(from, i);
      tokens.push({ type: 'number', value: Number(text), text, line: atLine, column: atColumn });
      continue;
    }

    if (startsName(source[i])) {
      while (i < source.length && inName(source[i])) advance();
      const text = source.slice(from, i);
      tokens.push({ type: 'name', value: text, text, line: atLine, column: atColumn });
      continue;
    }

    if ('{}=,'.indexOf(source[i]) !== -1) {
      const text = source[i];
      advance();
      tokens.push({ type: 'punct', value: text, text, line: atLine, column: atColumn });
      continue;
    }

    fail('unexpected character ' + JSON.stringify(source[i]), atLine, atColumn);
  }

  tokens.push({ type: 'end', value: '', text: '', line, column });
  return tokens;
}

const attempt = (fn) => { try { fn(); return null; } catch (err) { return err; } };

const config = [
  'till "Balogun 1" {',
  '  rate = 0.075   # VAT, as a fraction',
  '  items = 42',
  '}',
].join('\n');

const tokens = tokenise(config);
const placed = tokens.map((t) => t.value + '@' + t.line + ':' + t.column);
const kinds = [tokens.map((t) => t.type).join(' '), typeof tokens[5].value, tokens[5].value];
const commentGone = [tokens.some((t) => String(t.value).indexOf('#') !== -1), tokens[6].value, tokens[6].line];

const stray = attempt(() => tokenise('rate = 0.075\nitems = 42 ?\n}'));
const strayReport = [stray.name, stray.line, stray.column, stray.message];
const strayCaret = stray.caret.split('\n');

const open = attempt(() => tokenise('till "Balogun 1 {\n  rate = 1\n}'));
const openReport = [open.line, open.column, open.message];

const crlf = tokenise('a\r\nb').map((t) => [t.value, t.line, t.column]);

const lines = sourceLines(config);
let cutsBackOut = true;
for (const t of tokens) {
  if (!t.text) continue;
  if (lines[t.line - 1].slice(t.column - 1, t.column - 1 + t.text.length) !== t.text) cutsBackOut = false;
}

console.log('placed  :', placed.join(' '));
console.log('stray   :', strayReport);
console.log('caret   :');
console.log(stray.caret);
console.log('opened  :', openReport);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('every token carries the line and column it started at', placed, ['till@1:1', 'Balogun 1@1:6', '{@1:18', 'rate@2:3', '=@2:8', '0.075@2:10', 'items@3:3', '=@3:9', '42@3:11', '}@4:1', '@4:2']);
test('a number token holds a number, not the text it was cut from', kinds, ['name string punct name punct number name punct number punct end', 'number', 0.075]);
test('the comment leaves no token behind, and the next one is on the next line', commentGone, [false, 'items', 3]);
test('an unexpected character reports its own line and column, not an offset', strayReport, ['SyntaxError', 2, 12, 'unexpected character "?" at line 2, column 12']);
test('and the caret sits exactly under it', strayCaret, ['items = 42 ?', '           ^']);
test('an unterminated string reports where it OPENED, not where the input ended', openReport, [1, 6, 'unterminated string at line 1, column 6']);
test('a CRLF pair is one line break, not two', crlf, [['a', 1, 1], ['b', 2, 1], ['', 2, 2]]);
test('and every token can be cut back out of its own line using its own position', cutsBackOut, true);

A byte offset is not an error message. "Unexpected character at position 24" makes a reader count characters; "line 2, column 12" plus a caret makes the mistake obvious without leaving the message. The cost of that is one function: advance is the only code allowed to move i, so line and column cannot drift out of step with the index. Every tokeniser that reports positions badly has more than one place that increments the index.

The two locals captured before each token — atLine and atColumn — are the other half, and they are what makes the unterminated-string message useful. By the time you discover a string never closed you are at the end of the file, possibly hundreds of lines away, and that position is worthless: the reader needs the opening quote. Every good compiler error is a position remembered before the scan went wrong, not the position where it stopped.

The last assertion is a cheap way to keep a tokeniser honest. If a token's line and column can be used to slice its exact text back out of the source, the position bookkeeping is right for every token, not just the ones a test happened to name. It also catches the CRLF trap: treating \r\n as two breaks makes every subsequent line number one too high on a Windows-authored file, and this invariant fails immediately when it does.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.