Ohm v16

October 4, 2021

Ohm is a parsing toolkit for JavaScript, which I’ve been working on together with Alex Warth since 2014. Today we’re announcing Ohm v16.0.0! 🥳

Improved TypeScript support

Out of the box, Ohm mostly “just works” with TypeScript, and has for a while now. What’s new in Ohm v16 is that you can now generate type definitions for your grammars, which makes it much easier to work with semantic actions.

With grammar-specific types, the TypeScript compiler can check that your actions have the correct number of arguments and a consistent return type:

Screenshot from VS Code, showing a type error caused by the number action having too many parameters
Defining an action with too many arguments results in type error.

Also, IDEs such as VS Code can autocomplete action names, show tooltips with argument types (IterationNode, NonterminalNode, or TerminalNode), etc.:

Screenshot from VS Code, with a tooltip showing the argument types of the MulExp_divide action
Tooltip in VS Code showing the argument types of the MulExp_divide action.

How it works

To enable grammar-specific type definitions:

  1. Install the @ohm-js/cli package (e.g., npm install -D @ohm-js/cli to add it as a dev dependency).
  2. Put your grammar in a separate .ohm file, if it isn’t already.
  3. Use the Ohm CLI to generate a bundle (.ohm-bundle.js) for your grammar, along with the associated type definitions (.d.ts).

For example, if your grammar is in src/my-grammar.ohm:

npx ohm generateBundles --withTypes src

…will create src/my-grammar.ohm-bundle.js and src/my-grammar.ohm-bundle.d.ts. You can directly import the bundle like this:

import grammar from './my-grammar.ohm-bundle'

Then, when you create a semantics and use methods like addOperation, you’ll see that — based on the rules in your grammar — TypeScript knows what action names can appear in the action dictionary, and what the arguments to those actions are.

For more information, see the Ohm TypeScript example.

Upgrading

In order to make these TypeScript improvements, we also had to make some minor breaking changes to the Ohm API — see the changelog for all the details. If you need to upgrade existing code to support Ohm v16, take a look at the upgrade guide.

Getting help

If you have any questions about the new release, or need help upgrading your code to support Ohm v16, please check out the following resources:

Happy parsing!✌️