whynot.js Formal Language Matching Framework

5.0.0 · active · verified Sun Apr 19

whynot.js is a generic, VM-based framework for matching formal languages, drawing inspiration from systems like Russ Cox's regular expression engine. It operates by considering all possible branches of a program in parallel, enabling efficient implementation of various language matching tasks, including regular expressions and XML schemas. A key differentiator is its ability to record program progress through input and grammar, providing detailed feedback on *why* an input might not match a given grammar. The current stable version is 5.0.0, with releases focusing on performance, memory optimization, and module compatibility (ESM/CJS). While there isn't a strict release cadence, updates address bug fixes, dependency bumps, and significant architectural improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a basic VM program using `Instruction`s, initializing a `VM` with it, and executing an input array to check for a match. It shows both a matching and non-matching scenario.

import { Program, VM, Instruction, Trace } from 'whynot';

// Define a simple program that matches the sequence 'abc'
const program = new Program([
  Instruction.char('a'),
  Instruction.char('b'),
  Instruction.char('c'),
  Instruction.accept() // Signal successful match
]);

// Initialize the VM with the program
const vm = new VM(program);

// Execute the VM against an input array of characters
const input1 = ['a', 'b', 'c'];
const trace1: Trace | null = vm.execute(input1);

if (trace1) {
  console.log(`Input '${input1.join('')}' matched successfully.`);
  // You can inspect the trace for details on the match path
  // console.log('Trace records:', trace1.records);
} else {
  console.log(`Input '${input1.join('')}' did NOT match.`);
}

const input2 = ['a', 'x', 'c'];
const trace2: Trace | null = vm.execute(input2);

if (trace2) {
  console.log(`Input '${input2.join('')}' matched successfully.`);
} else {
  console.log(`Input '${input2.join('')}' did NOT match.`);
}

view raw JSON →